Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java recursion with one return statement

Tags:

java

recursion

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);
}
like image 877
DCR Avatar asked Mar 22 '19 14:03

DCR


3 Answers

return n == 1 ? n : n + sum(n-1);
like image 55
Grégory Elhaimer Avatar answered Oct 04 '22 06:10

Grégory Elhaimer


You could use simple maths without recursion:

public static int sum(int n) {
   return n * (n + 1) / 2;
}
like image 42
Lino Avatar answered Oct 04 '22 07:10

Lino


Yes, by making use of the ternary operator :

public static int sum(int n) {
    return n == 1 ? n : n + sum(n - 1);
}
like image 42
Nicholas Kurian Avatar answered Oct 04 '22 05:10

Nicholas Kurian