Sum of Natural Numbers
Published at25 Jul 2026
Created by M Ichsanul Fadhil
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
Solution Approach
Best Answers
java
class Solution {
public int solution(int n) {return n*(n+1)/2;}
}Related Math Challenges
Comments (0)
Join the Discussion
Share your thoughts, ask questions, or help others with this Challenge.
