Code Logo

Sum of Natural Numbers

Published at25 Jul 2026
Basic Operations Easy 0 views
Like0

Given a positive integer n, return the sum of all natural numbers from 1 to n (inclusive). Use the formula n * (n + 1) / 2 instead of a loop for O(1) time.

Example Input & Output

Example 1
Input
10
Output
55
Explanation

1+2+...+10=55

Example 2
Input
3
Output
6
Explanation

1+2+3=6

Example 3
Input
5
Output
15
Explanation

1+2+3+4+5=15

Example 4
Input
0
Output
0
Explanation

Empty sum

Example 5
Input
1
Output
1
Explanation

Just 1

Algorithm Flow

Recommendation Algorithm Flow for Sum of Natural Numbers
Recommendation Algorithm Flow for Sum of Natural Numbers

Solution Approach

function solution(n) {
  return n * (n + 1) / 2;
}

Best Answers

java
class Solution {
    public int solution(int n) {return n*(n+1)/2;}
}