vucko95 - 5 months ago 12x

Java Question

I have to find sum of the all even numbers that are not divisible by 7 using recursion. I tried this code but it seems I am making mistake somewhere because it returns 0:

`public static void main(String[] args) {`

System.out.println(specialSum(50));

}

public static int specialSum(int a) {

if ((a >= 1) && ((specialSum(a-1))%7 !=0)) {

return a + specialSum(a -1);

} else{

return 0;

}

}

}

Answer

Here you have the solution in one line, you should have a case to stop the recursion, in your case you stop the recursion at 49 because it is divisible by 7, and you don't take into account numbers less than 49

```
main()
{
specialSum(50, 7);
}
public static int specialSum(int a, int toDivide)
{
return (a == 0) ? 0 : (a >= 1 && a%2 == 0 && a%7 != 0) ? a + specialSum(a - 1, toDivide) : specialSum(a - 1, toDivide);
}
```

Source (Stackoverflow)

Comments