Is it possible to add the numbers 1 to n recursively in Java with one return statement? How would you change the standard solution:
public static int sum(int n) {
if(n == 1) return n;
else return n + sum(n - 1);
}
You could use simple maths without recursion:
public static int sum(int n) {
return n * (n + 1) / 2;
}
>> 1. There's no need to, though. The compiler will make this trivial optimization on its own. Exploiting integer overflow is bizarre.