Skip to content
Problem 829 · LeetCode 829(opens in a new tab)

Consecutive Numbers Sum

HardMath

Given a positive whole number n, count the ways to write it as a sum of one or more consecutive positive integers, such as 7 + 8 or 3 + 4 + 5 + 6.

n on its own counts as one way (a run of length 1). Two ways are different when they use different runs of numbers.

Example 1

Input:  n = 21
Output: 4
Why:    21, 10 + 11, 6 + 7 + 8 and 1 + 2 + 3 + 4 + 5 + 6
2 more examples and the constraints

Example 2

Input:  n = 16
Output: 1
Why:    only 16 itself; a power of 2 has no other run

Example 3

Input:  n = 90
Output: 6
Why:    runs of length 1, 3, 4, 5, 9 and 12

Constraints

  • 1 ≤ n ≤ 1,000,000,000

Your turn first

Have a go on paper or in your own editor, then reveal the approaches from the simplest up.

Try it on LeetCode(opens in a new tab)
  1. Try every run lengthO(√n)
  2. Count the odd divisorsO(√n)

The idea in one sentence

The pattern, how to spot it, and the best complexity.

Side by side

ApproachTimeRelative work for n = 1,000,000,000 (worst case)Verdict
Try every run lengthO(√n)
Clear; easy to derive
Count the odd divisorsO(√n)
Best; odd d only, n shrinks

n = the target number.

Edge cases to test

  • n = 1. Only the run [1], so the answer is 1.
  • Powers of 2. 16 or 1,024 have no odd divisor except 1: the answer is 1.
  • Odd prime. 13 = 13 = 6 + 7: exactly 2 ways.
  • Upper limit. 1,000,000,000 = 2⁹ × 5⁹ has 10 odd divisors, so 10 ways.
  • Overflow in k(k + 1). Near the limit k reaches about 44,721, and k(k + 1) passes the int range; use a 64-bit k.

Common mistakes

  • Counting runs that start at 0 or below; the numbers must be positive.
  • Forgetting that n alone is a run of length 1.
  • Computing k·(k + 1) in a 32-bit int, which overflows near n = 10⁹.

How to talk through it

  1. 1Clarify. Does n by itself count? Must every number be positive?
  2. 2Write the sum. k numbers from a sum to k·a + k(k − 1)/2; that turns a search into a divisibility test.
  3. 3Bound k. The smallest run of length k is k(k + 1)/2, so k stays below √(2n).
  4. 4Mention the divisor view. 2n = k(2a + k − 1) with one odd factor: count odd divisors of n.
  5. 5Test out loud. Run n = 1, 16 and 21, and say why 10⁹ needs 64-bit k.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?