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: n = 9Find all ways to write 9 as sum of consecutive positive integersWay 1: 9Way 2: 4 + 5Way 3: 2 + 3 + 41+2+3+4 = 10Too big ✗Single numberTwo consecutiveThree consecutiveFour consecutiveAnswer: 3 ways
Understanding the Visualization
1
Input
Given n = 9
2
Find Sequences
Look for consecutive number sequences that sum to 9
3
Count Ways
Return total number of valid sequences
Key Takeaway
🎯 Key Insight: Use arithmetic sequence formula to check if each sequence length can produce valid consecutive integers
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