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.
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:
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:
If you want the sum you should return specialSum(x-1)+x
not 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.
you have to change the specialsum method like this:
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 );
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.