Magicsheet logo

Consecutive Numbers Sum

Hard
12.5%
Updated 8/1/2025

Consecutive Numbers Sum

What is this problem about?

The Consecutive Numbers Sum interview question is a challenging mathematical problem. Given a positive integer N, you need to find the number of ways it can be written as a sum of consecutive positive integers. For example, 9 can be written as 9 (one number), 4+5 (two numbers), or 2+3+4 (three numbers).

Why is this asked in interviews?

This Consecutive Numbers Sum coding problem is frequently asked by quantitative trading firms like Citadel and tech giants like Google. It tests mathematical intuition and the ability to derive an optimized solution from a brute-force idea. It moves the focus from standard data structures to algebraic manipulation.

Algorithmic pattern used

This utilizes the Math, Enumeration interview pattern. The core idea is to represent the sum of k consecutive integers starting from x as: N = x + (x+1) + (x+2) + ... + (x+k-1) N = kx + k(k-1)/2 Rearranging this gives: kx = N - k(k-1)/2. For a valid sequence to exist, N - k(k-1)/2 must be positive and divisible by k.

Example explanation

Let's find the ways for N = 15.

  1. For k=1 (15): 15 - 0 = 15, divisible by 1. (Yes: 15)
  2. For k=2: 15 - 1 = 14, divisible by 2. (Yes: 7+8)
  3. For k=3: 15 - 3 = 12, divisible by 3. (Yes: 4+5+6)
  4. For k=4: 15 - 6 = 9, not divisible by 4. (No)
  5. For k=5: 15 - 10 = 5, divisible by 5. (Yes: 1+2+3+4+5)
  6. For k=6: 15 - 15 = 0, not positive. (Stop) Total = 4 ways.

Common mistakes candidates make

  • Brute force: Trying all possible start and end points (O(N^2)), which is impossible for N = 10^9.
  • Not defining the loop bound: Iterating up to N instead of roughly sqrt(2N), which is where the term k(k-1)/2 exceeds N.
  • Integer overflow: Not considering that calculations like k(k-1) can be large.

Interview preparation tip

When you see a problem involving sums of sequences, try to write down the arithmetic series formula. Simplifying the algebra often reduces a complex search problem into a simple loop over a few possible values.

Similar Questions