有人可以解释一下这是如何为每个整数返回正确的布尔值的吗?

huangapple go评论154阅读模式
英文:

Can someone explain me how is this returning the correct boolean value for every integer?

问题

我正在努力理解在我设置一个数字后它是如何返回正确的值的,但我没有理解它的功能。

public static boolean isEven(int n){
        if (n==1){
            return false;
        }else {
            return !isEven(n-1);
        }

    }
英文:

I am trying to understand how it is returning the correct value after i set a number, but didnt grasp what it does .

public static boolean isEven(int n){
        if (n==1){
            return false;
        }else {
            return !isEven(n-1);
        }

    }

答案1

得分: 2

这是一个递归函数。递归需要两个要素:一个基本情况和向基本情况的推进。在这种情况下,基本情况是 n==1,通过每次调用函数时减少输入来向基本情况推进。在达到基本情况之前不会返回任何值。无论输入什么整数作为参数,它都会在返回任何内容之前被减少为1。一旦达到1,将返回false。然后,每个递归调用将按照从调用它们的相反顺序返回。因为它们将返回 !isEven(n),所以每次调用都会交替返回true和false,就像每个整数交替为true或false一样。因此,最终的返回值将始终是正确的。

示例:n = 4

isEven(4)
   isEven(3) 
      isEven(2)
          isEven(1) -> 返回false
      isEven(2) -> 返回true
   isEven(3) -> 返回false
isEven(4) -> 返回true

有关递归基础的更多信息,请参阅 https://www.tutorialspoint.com/data_structures_algorithms/recursion_basics.htm

英文:

This is a recursive function. Recursion requires two things. A base case and progression toward the base case. In this instance the base case is n==1 and progression is made toward the base case by decrementing the input each time the function is called. Nothing is returned until the base case is reached. Whatever Integer is input as a parameter it will be reduced to 1 before returning anything. Once 1 is reached false will be returned. Then every recursive call will return in reverse order from when they were called. Since they will return !isEven(n) each call will alternate true and false, just like every integer alternates being true or false. So the final return value will always come out correct.

Example: n = 4

isEven(4)
   isEven(3) 
      isEven(2)
          isEven(1) -> returns false
      isEven(2) -> return true
   isEven(3) -> returns false
isEven(4) -> returns true

For more on the basics of recursion https://www.tutorialspoint.com/data_structures_algorithms/recursion_basics.htm

答案2

得分: 1

你可以从以下两个示例中理解它:

  1. 调用 isEven(3)

     isEven(3) => !isEven(2) => !isEven(1)
                             返回 !false,即 true
                  返回 !true,即 false
    
  2. 调用 isEven(4)

     isEven(4) => !isEven(3) => !isEven(2) => !isEven(1)
                                         返回 !false,即 true
                       返回 !true,即 false
                  返回 !false,即 true
    
英文:

You can understand it from the following two examples:

  1. Call isEven(3)

    isEven(3) => !isEven(2) => !isEven(1)
    							returns !false i.e. true
    			 returns !true i.e. false
    
  2. Call isEven(4)

    isEven(4) => !isEven(3) => !isEven(2) => !isEven(1)
    										returns !false i.e. true
    						  returns !true i.e. false
    			 returns !false i.e. true
    

答案3

得分: 1

这就像一个循环,根据数字的次数来不断更改布尔值。所以当数字为5时,它从false开始,因为它不是1,然后它会更改4次:
false -> true -> false -> true -> false

对于 n = 5

if (n == 1) {
    return false;
} else {
    return !isEven(n-1);
}

与以下表达式的功能相同

return !(!(!(!(false))));
英文:

It works like a loop, which is changing the boolean as often as the number. So when the number is 5, it starts with false, because it isn't 1 and then it just changes 4 times:
false -> true -> false -> true -> false

For n = 5:

if (n == 1) {
    return false;
} else {
    return !isEven(n-1);
}

works the same as

return !(!(!(!(false))));

答案4

得分: 1

为了理解递归过程,请查看递归的含义。在这种情况下,假设语句"isEven()给出了正确的结果"是真实的,并看看正在发生什么。

  • 如果n - 1是偶数,则isEven(n - 1)为真;而n是奇数,因此返回的结果是正确的。
  • 如果n - 1是奇数,则isEven(n - 1)为假;n是偶数,因此在这种情况下结果也是正确的。
  • 如果n == 1,则n是奇数,所以结果是正确的(并且在没有递归的情况下计算,这是基本情况)。
  • 每次对isEven()的递归调用都是使用较小的n进行的,因此递归调用使您(向基本情况)靠近一步。因此,您肯定最终会达到1,递归不会永远进行。

这本质上是通过归纳法证明,微妙地伪装起来。


退后一步:每当您尝试理解调用其他函数的函数时,首先假设其他函数会正确地完成其工作并(最终)给出正确的答案,然后从那里开始工作。在您确信所审查的函数是正确的之后,您会转向所调用的函数。在某个点上,您会达到微不足道的函数,或者按信仰认为语言提供的操作是正确的。

同样的道理适用于这里:假设所调用的函数对于给定的参数会执行其工作(不管它是否是我们正在分析的相同函数),并且(在这种情况下是递归的)调用的结果被正确地组合起来。检查是否存在基本情况(没有递归调用),并且这些调用使您“靠近”基本情况。

英文:

To undestand recursive procedures, check what the recursion says. In this case, assume the statement "isEven() gives the right result" is true, and take a look at what is going on.

  • If n - 1 is even, isEven(n - 1) is true; and n is odd, so the result returned is right.
  • If n - 1 is odd, isEven(n - 1) is false; n is even, so the result is right in this case too.
  • If n == 1, n is odd, so the result is right (and is computed without recursion, base case).
  • Each recursive call to isEven() is a call with a smaller n, so your recursive calls get you (one step) nearer to the base case. Thus you are sure to reach 1 eventually, the recursion doesn't go on forever.

This is essentially a proof by induction, thinly disguised.


Take a step back: Whenever you try to understand a functions that calls other functions, as a first cut you assume the other functions do their job right and (eventually) give the right answer, and work from there. After you have convinced yourself that the scrutinized function is right, you go for the functions called. At some point you reach trivial functions or take the operations provided by the language as correct by faith.

Same here: Assume the called function for the arguments given does it's job (doesn't matter it is the same function we are analyzing), and the results of the (in this case recursive) calls are combined correctly. Check there are base cases (no recursive calls), and that the calls get you "closer" to the base cases.

huangapple
  • 本文由 发表于 2020年8月18日 06:48:49
  • 转载请务必保留本文链接:https://go.coder-hub.com/63459614.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定