← Questions

Count ways to write N as a sum of consecutive positive integers

0
AirbnbCodingLast asked Apr 2026

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 n be? (It rules out trying every start.)

What a strong answer covers

  • A run of k terms starting at a sums to k*a + k*(k-1)/2. For each k while k*(k+1)/2 <= n, check whether n - k*(k-1)/2 is a positive multiple of k. 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 n quickly.

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

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