Consecutive Numbers Sum - Problem

Given an integer n, return the number of ways you can write n as the sum of consecutive positive integers.

A consecutive sequence means the integers are in order: 1, 2, 3 or 5, 6, 7, 8, etc.

Example: n = 9 can be written as:

  • 9 (single number)
  • 4 + 5 (two consecutive numbers)
  • 2 + 3 + 4 (three consecutive numbers)

So the answer is 3 ways.

Input & Output

Example 1 — Basic Case
$ Input: n = 9
Output: 3
💡 Note: Three ways: 9 (single), 4+5 (two consecutive), 2+3+4 (three consecutive)
Example 2 — Small Number
$ Input: n = 15
Output: 4
💡 Note: Four ways: 15, 7+8, 4+5+6, 1+2+3+4+5
Example 3 — Power of 2
$ Input: n = 8
Output: 1
💡 Note: Only one way: 8 (powers of 2 can only be expressed as single number)

Constraints

  • 1 ≤ n ≤ 109

Visualization

Tap to expand
Consecutive Numbers Sum INPUT n = 9 Find all ways to write 9 as sum of consecutive positive integers Possible Representations: 9 4 + 5 2 + 3 + 4 Input: n = 9 ALGORITHM STEPS 1 Use Math Formula Sum = k*a + k*(k-1)/2 where k = length, a = start 2 Rearrange for 'a' a = (n - k*(k-1)/2) / k a must be positive integer 3 Iterate k from 1 Stop when k*(k-1)/2 >= n Check if a is valid 4 Count Valid Cases If (n-k*(k-1)/2) % k == 0 and result > 0, count++ Checking for n=9: k=1: (9-0)/1=9 OK a=9 k=2: (9-1)/2=4 OK a=4 k=3: (9-3)/3=2 OK a=2 k=4: (9-6)/4=0.75 NO FINAL RESULT 3 ways found The 3 Valid Representations: Way 1 (k=1): 9 = 9 Way 2 (k=2): 9 = 4 + 5 Way 3 (k=3): 9 = 2 + 3 + 4 Output: 3 Key Insight: For k consecutive numbers starting at a: Sum = k*a + k*(k-1)/2 = n. Rearranging: a = (n - k*(k-1)/2) / k. We iterate k from 1 until k*(k-1)/2 >= n, counting cases where 'a' is a positive integer. Time: O(sqrt(n)) This mathematical approach avoids brute force iteration and provides an optimal solution. TutorialsPoint - Consecutive Numbers Sum | Optimal Solution O(sqrt(n))
Asked in
Google 25 Microsoft 18
28.0K Views
Medium Frequency
~15 min Avg. Time
890 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen