#829

Consecutive Numbers Sum

Hard Number theory

  1. Read
  2. Understand
  3. Hints
  4. Approach
  5. Solution
  6. Solved

?The problem

Count the ways to write n as a sum of one or more consecutive positive integers.

This is a short summary in our own words. Read the full statement and examples on LeetCode: open problem ↗

◎Understanding

Really asking: in how many ways is n a sum of a run of consecutive positive numbers?

Why this works: a run of length k starting at x sums to k·x + k(k-1)/2. For a fixed k, solve for x and check it's a positive whole number. k only goes up to about √(2n).

Example: n = 9

k=1: 9 % 1 = 0 → [9]k=2: (9-1) % 2 = 0 → [4,5]k=3: (9-3) % 3 = 0 → [2,3,4]k=4: (9-6) % 4 ≠ 0answer: 3

✦Hints open one at a time

↗Approach

</>Solution (Java)

!Common mistake

Looping x over all starting values — that's O(n) or worse and times out for n up to 10^9.