5

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);
}
0

4 Answers 4

13
return n == 1 ? n : n + sum(n-1);
Sign up to request clarification or add additional context in comments.

Comments

6

You could use simple maths without recursion:

public static int sum(int n) {
   return n * (n + 1) / 2;
}

3 Comments

Wow, that’s an amazing formula did you figure that out yourself?
@DCR This problem has been known for quite a while, this formula is widely accessible on the internet
If you want to get rid of the division use >> 1. There's no need to, though. The compiler will make this trivial optimization on its own. Exploiting integer overflow is bizarre.
3

Yes, by making use of the ternary operator :

public static int sum(int n) {
    return n == 1 ? n : n + sum(n - 1);
}

Comments

0
  public static int sum(int n) {
      return n == 1 ? 1 : n + sum(n-1);
  }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.