← Questions
Count ways to write N as a sum of consecutive positive integers
0
I was asked this
No reports yet. Sign in to say where you were asked it.
A coding interview question asked in Airbnb's coding round, last asked Apr 2026. It tests math and number theory.
Given a positive integer n, return how many ways it can be written as a sum of one or more consecutive positive integers. n on its own counts as one way.
Interface
Unless you agree on a different interface with the interviewer, assume:
count_consecutive_sums(n: int) -> int
Example
n = 9 -> 3 # 9, 4 + 5, 2 + 3 + 4
n = 15 -> 4 # 15, 7 + 8, 4 + 5 + 6, 1 + 2 + 3 + 4 + 5
n = 16 -> 1 # only 16
n = 45 -> 6
Constraints
1 <= n <= 10^12- Terms increase by exactly one, and every term is positive.
Clarifying questions
- Does the single-term sum count?
- Should I return the sums or only the count?
- How large can
nbe? (It rules out trying every start.)
What a strong answer covers
- A run of
kterms starting atasums tok*a + k*(k-1)/2. For eachkwhilek*(k+1)/2 <= n, check whethern - k*(k-1)/2is a positive multiple ofk. That is O(sqrt(n)). - The number theory behind it: the answer equals the number of odd divisors of
n, so factor out the twos and count divisors of the odd part. - Why powers of two have exactly one way.
- Tests: 1, a power of two, a prime, a large
n.
Follow-ups
- List the sums themselves.
- Count ways using at least two terms.
- Answer many queries for different
nquickly.
Where it's asked
- Airbnb · Coding · Last asked Apr 202645 min · Live coding, one or two rounds, from the same pool as the screen
What it tests
math · number theory
No official answer yet. Write yours on the right and run it.
Nothing published yet.
Sign in to submit your code; every attempt is kept here.
Write and test your solution herePython in your browser, the question's tests level by level, every submission kept for you.Sign in to start coding
