Consecutive Numbers Sum - Problem
Consecutive Numbers Sum

Given a positive integer n, determine how many different ways you can express n as the sum of consecutive positive integers.

For example, the number 9 can be written as:
9 (single number)
4 + 5 (two consecutive numbers)
2 + 3 + 4 (three consecutive numbers)

So there are 3 ways to write 9 as a sum of consecutive positive integers.

Your task: Return the total count of such representations for any given positive integer n.

Input & Output

example_1.py — Basic Case
$ Input: n = 5
Output: 2
💡 Note: 5 can be written as: (1) 5 itself, (2) 2 + 3. So there are 2 ways total.
example_2.py — Multiple Ways
$ Input: n = 9
Output: 3
💡 Note: 9 can be written as: (1) 9 itself, (2) 4 + 5, (3) 2 + 3 + 4. So there are 3 ways total.
example_3.py — Single Way
$ Input: n = 3
Output: 2
💡 Note: 3 can be written as: (1) 3 itself, (2) 1 + 2. So there are 2 ways total.

Visualization

Tap to expand
Consecutive Numbers Sum: Breaking Down n=9Method: Mathematical Formula ApproachSequence Length k=1:start = (9 - 1×0/2) ÷ 1 = 9 ✓9Sequence Length k=2:start = (9 - 2×1/2) ÷ 2 = 4 ✓45Sequence Length k=3:start = (9 - 3×2/2) ÷ 3 = 2 ✓234Sequence Length k=4:start = (9 - 4×3/2) ÷ 4 = 0.75 ✗ (not integer)Total Valid Ways: 3
Understanding the Visualization
1
Single Piece
The number itself (always valid)
2
Two Pieces
Check if n can be split into two consecutive numbers
3
Three Pieces
Check if n can be split into three consecutive numbers
4
Continue
Keep checking until sequences become impossible
Key Takeaway
🎯 Key Insight: Use the arithmetic sequence formula sum = k × start + k × (k-1) / 2 to directly calculate if a sequence of length k is possible, reducing time complexity from O(n²) to O(√n)

Time & Space Complexity

Time Complexity
⏱️
O(n²)

For each starting position (O(n)), we may check up to O(n) consecutive numbers

n
2n
Quadratic Growth
Space Complexity
O(1)

Only using a few variables to track count and current sum

n
2n
Linear Space

Constraints

  • 1 ≤ n ≤ 109
  • n is a positive integer
  • Time limit: 1 second per test case
Asked in
Google 45 Microsoft 38 Amazon 32 Meta 28
28.8K Views
Medium Frequency
~25 min Avg. Time
1.2K 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