Sum of Natural Numbers
Given a non-negative integer n, compute the sum of all natural numbers from 1 to n inclusive. The formula is: sum = 1 + 2 + 3 + ... + n = n × (n + 1) / 2.
For example, the sum of numbers from 1 to 5 is 1 + 2 + 3 + 4 + 5 = 15. Using the formula: 5 × 6 / 2 = 30 / 2 = 15. For n = 0, the sum is 0. For n = 1, the sum is 1.
This problem introduces the concept of arithmetic series and the famous formula attributed to Carl Friedrich Gauss. Legend has it that young Gauss discovered this formula when his teacher asked the class to sum the numbers from 1 to 100 — Gauss recognized the pattern and solved it instantly. The formula is used extensively in algorithm analysis (summation of O(n) operations), combinatorics, and series calculations.
A naive implementation would use a loop to accumulate the sum, which runs in O(n) time. The formula approach runs in O(1) time and is preferable for efficiency, especially for large n. The formula n × (n + 1) / 2 works for all non-negative n, including n = 0 where the result is 0.
When implementing the formula, be careful with integer overflow: n × (n + 1) can overflow for large n before the division by 2 brings the result back into range. For the constraints of this challenge, standard 32-bit integers are sufficient.
Example Input & Output
1+2+...+10=55
1+2+3=6
1+2+3+4+5=15
Empty sum
Just 1
Algorithm Flow
Solution Approach
Use the arithmetic series formula n * (n + 1) / 2 for an O(1) solution.
The formula n * (n + 1) / 2 computes the sum directly without iteration. For n = 5: 5 * 6 / 2 = 30 / 2 = 15. For n = 0: 0 * 1 / 2 = 0. The integer division truncates correctly because either n or n + 1 is always even, so the product is always divisible by 2.
A loop-based alternative is also valid but runs in O(n) time:
The formula approach is preferred for its constant-time performance. Time complexity is O(1), space complexity is O(1).
Best Answers
class Solution {
public int solution(int n) {return n*(n+1)/2;}
}Comments (0)
Join the Discussion
Share your thoughts, ask questions, or help others with this Challenge.
