简体   繁体   English

带返回的递归方法

[英]Recursive method with return

I have to write a recursive method that will count the sum of all even numbers that can not be divided with 7 in an interval form 1 till a parameter. 我必须编写一个递归方法,该方法将计算无法将间隔数为1 7除以偶数的所有偶数之和,直到一个参数为止。

I cant use any loop. 我不能使用任何循环。 This is how far I came, but it seems that my statement is not correct. 这就是我走的路,但是看来我的说法是不正确的。

Any suggestions? 有什么建议么?

public static int specialSum (int x){
    return (x % 2 == 0) && (x % 7 != 0) ? specialSum(x - 1) + 1 : 0;
}

public static void main(String[] args) {
    System.out.println(specialSum(16));
}

You need to recurse to the next number whether or not you count the current one. 无论是否计算当前数字,都需要递归到下一个数字。

boolean divisibleBy2Not14 = ((x % 2 == 0) && (x % 7 != 0);
return (divisibleBy2Not14 ? x : 0) + (x > 0 ? specialSum(x - 1) : 0);

If you need to find the sum of such ( x % 2 == 0 && x % 7 != 0 ) positive ( x > 0 ) numbers: 如果你需要找到这样的总和( x % 2 == 0 && x % 7 != 0 ),正( x > 0 )的数字:

public static int specialSum (int x) {
    return x > 0 ?
            specialSum(x - 1) + (x % 2 == 0 && x % 7 != 0 ? x : 0) :
            0;
}

The logic of your recursive has two problems: 递归的逻辑有两个问题:

  1. It's trying to return the count and not the sum of number that are valid 它试图返回计数而不是有效的数字总和
  2. And the recursion does not reach all the branches, because it's terminated as soon as it reaches a non-valid case. 而且,递归不会到达所有分支,因为一旦到达无效案例,它就会被终止。

If you want the sum you should return specialSum(x-1)+x not specialSum(x-1)+1 . 如果需要总和,则应返回specialSum(x-1)+x而不是specialSum(x-1)+1 This is an example that would work: 这是一个可行的示例:

public static int specialSum (int x){
    if(x == 0) return 0; // ← degenerate case
    return ((x % 2 == 0) && (x % 7 != 0) ? specialSum(x - 1) + x : specialSum(x - 1));
}

You could add a little clever simplification by replacing specialSum(x - 1) + x by specialSum(x - 2) + x , because you know that x - 1 is going to be odd if x is even. 你可以通过替换加小聪明简化specialSum(x - 1) + xspecialSum(x - 2) + x ,因为你知道, x - 1将是奇怪的,如果x是偶数。

you have to change the specialsum method like this: 您必须像这样更改specialsum方法:

public static int specialSum (int x){
    if(x == 1)  return 0;
    return ((x % 2 == 0) && (x % 7 != 0) ? specialSum(x - 1) + x   : specialSum(x - 1));
}

A good way to approach it is to first write it out the long way (no ternary operators). 处理它的一个好方法是首先将其写得很长(没有三元运算符)。 Then you can see if it can be shortened: 然后,您可以查看它是否可以缩短:

   public static int summer( int n ) {
      if ( n < 2 ) {
         return 0;
      } else if ( (n % 2) == 0 ) {
         if ( (n % 7) == 0 ) {
            return summer( n - 2 ); // n-1 is odd, so skip it
         }
         return n + summer( n - 2 ); // n-1 is odd, so skip it
      } else {
         return summer( n - 1 );
      }
   }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM