Consecutive Numbers Sum

Hard Arrays & Hashing Math / Number Theory

Consecutive Numbers Sum is a hard arrays & hashing problem solved with the math / number theory pattern. The best approach, optimal (count the odd divisors), runs in O(sqrt(n)) time and O(1) space. Below are 3 approaches in Java, Python, C++ and JavaScript, from brute force (try every starting number) up.

Problem

Given a positive integer n, count the number of different ways to write n as the sum of one or more consecutive positive integers.

A way is a run like a + (a + 1) + ... + (a + k - 1) with a >= 1 and k >= 1. The number n on its own counts as a run of length one. Two ways are different when their runs are different; the order of the terms inside a run does not create a new way.

Return the number of ways.

Examples

Example 1

Input
n = 5
Output
2
Why
5 on its own is one way, and 2 + 3 is the other. No run of three or more positive integers adds up to 5, because the smallest such run, 1 + 2 + 3, is already 6.

Example 2

Input
n = 9
Output
3
Why
The three ways are 9, 4 + 5 and 2 + 3 + 4.

Example 3

Input
n = 15
Output
4
Why
15, 7 + 8, 4 + 5 + 6 and 1 + 2 + 3 + 4 + 5 all add up to 15.

Constraints

  • 1 <= n <= 10^9

Solve it here

Write your solution in Java, Python, C++ or JavaScript and run it against the examples, right in the page. Submit runs the hidden tests too and, with a free account, records the solve in your revision log.

00:00
Testcase

Run checks the testcases above (3 examples, or your own). Submit also runs 17 hidden tests and saves the solve to your log. Signed in, every Run and Submit is saved under My submissions; your draft stays in this browser.

Animated walkthrough

A narrated, step-by-step animation that builds the solution from the idea up. Press play, or step through it at your own pace.

Concepts first, then the problem and every approach, step by step.

Space to play or pause · ← → to jump a step · click or drag the bar to seek

Solutions

Try it yourself first. Then compare: each approach lists its idea, the steps, its time and space, and the code in Java, Python, C++ and JavaScript.

ApproachTimeSpace
Brute force (try every starting number)O(n log n)O(1)
Try every lengthO(sqrt(n))O(1)
Optimal (count the odd divisors)O(sqrt(n))O(1)

1Brute force (try every starting number)

TimeO(n log n)For start s the inner loop runs at most about min(sqrt(2n), n / s) times. The small starts cost sqrt(2n) each and the rest add up to about n times a logarithm. With n = 10^9 that is tens of billions of additions.
SpaceO(1)Only a sum and a counter.

Try every possible first number of the run. From a start s, keep adding s, s + 1, s + 2 and so on until the sum reaches or passes n. If it lands exactly on n, that start gives one way. The idea is simple and correct, but n can be a billion, so even the outer loop alone is far too slow.

  1. Set ways = 0.
  2. For each start from 1 to n: add consecutive numbers to a sum, starting at start, while the sum is below n.
  3. If the sum equals n, add one to ways.
  4. Return ways.
class Solution {
    public int consecutiveNumbersSum(int n) {
        int ways = 0;
        for (int start = 1; start <= n; start++) {
            long sum = 0;
            for (int x = start; sum < n; x++) sum += x;
            if (sum == n) ways++;
        }
        return ways;
    }
}

2Try every length

TimeO(sqrt(n))k * (k + 1) / 2 <= n allows k up to about sqrt(2n), and each length costs one division.
SpaceO(1)Only the loop counter and the count.

Turn the search around and fix the length k of the run instead of its start. A run of k numbers starting at a adds up to k * a + (0 + 1 + ... + (k - 1)) = k * a + k * (k - 1) / 2. Setting that equal to n gives a = (n - k * (k - 1) / 2) / k, so a length k works exactly when n - k * (k - 1) / 2 is divisible by k and the start a is at least 1. The condition a >= 1 is the same as k * (k + 1) / 2 <= n: the run 1 + 2 + ... + k is the smallest run of length k. That stops the loop at about sqrt(2n), roughly 44,700 lengths for n = 10^9.

  1. Set ways = 0.
  2. For k = 1, 2, 3, ... while k * (k + 1) / 2 <= n:
  3. If (n - k * (k - 1) / 2) % k == 0, the start a is a whole number, so add one to ways.
  4. Return ways.
class Solution {
    public int consecutiveNumbersSum(int n) {
        int ways = 0;
        for (long k = 1; k * (k + 1) / 2 <= n; k++) {
            if ((n - k * (k - 1) / 2) % k == 0) ways++;
        }
        return ways;
    }
}

3Optimal (count the odd divisors)

TimeO(sqrt(n))Trial division only goes up to the square root of the odd part, stepping over even numbers, and every division shrinks n. It is fastest when n has small factors, and about sqrt(n) / 2 steps when the odd part is prime.
SpaceO(1)Only the divisor, its exponent and the count.

Double the sum formula: 2n = k * (2a + k - 1). The two factors differ by 2a - 1, an odd number, so one of them is odd and the other is even, and the even one must hold every factor of two in 2n. Pick any odd divisor d of n. Pair it with 2n / d, which is even; call the smaller of the two k and the larger 2a + k - 1. That gives a valid run with a >= 1, and different odd divisors give different runs. So the answer is simply the number of odd divisors of n. Divide out all the twos, factor what is left as p1^e1 * p2^e2 * ..., and the count is (e1 + 1) * (e2 + 1) * ...: each prime can appear in a divisor 0 to e times.

  1. While n is even, divide it by 2. The twos never matter.
  2. Set ways = 1. For each odd p = 3, 5, 7, ... while p * p <= n: count how many times p divides n (e), divide them out, and multiply ways by e + 1.
  3. If what is left is greater than 1, it is one more prime with exponent 1: multiply ways by 2.
  4. Return ways.
class Solution {
    public int consecutiveNumbersSum(int n) {
        while (n % 2 == 0) n /= 2;
        int ways = 1;
        for (int p = 3; (long) p * p <= n; p += 2) {
            int e = 0;
            while (n % p == 0) {
                n /= p;
                e++;
            }
            ways *= e + 1;
        }
        if (n > 1) ways *= 2;
        return ways;
    }
}

Edge cases to test

  • n = 1: only the number 1 itself, so the answer is 1
  • n is a power of two (2, 4, 8, ..., 2^29): no run of two or more numbers works, so the answer is 1
  • n is an odd prime: n itself and the pair (n - 1) / 2 + (n + 1) / 2, so the answer is 2
  • The single number n always counts as a run of length one, so the answer is never 0
  • Runs must use positive integers: allowing 0 or negative numbers would add extra, invalid runs
  • n up to 10^9 rules out trying every starting number; even k * (k + 1) / 2 is safest computed in a long

Hints

Hint 1

A run of k consecutive numbers starting at a adds up to k * a + k * (k - 1) / 2. Fix k instead of a.

Hint 2

For a fixed length k, the start is a = (n - k * (k - 1) / 2) / k. It must be a whole number and at least 1, and a >= 1 means k * (k + 1) / 2 <= n, so k only goes up to about the square root of 2n.

Hint 3

Multiply by two: 2n = k * (2a + k - 1). The two factors have opposite parity, so every way matches one odd divisor of n. Count the odd divisors from the prime factorization.

FAQ

What is the best time complexity for Consecutive Numbers Sum?

Optimal (count the odd divisors) runs in O(sqrt(n)) time and O(1) extra space. Trial division only goes up to the square root of the odd part, stepping over even numbers, and every division shrinks n. It is fastest when n has small factors, and about sqrt(n) / 2 steps when the odd part is prime.

Which pattern does Consecutive Numbers Sum use?

It is a arrays & hashing problem that uses the math / number theory pattern. Other problems with the same pattern: Bulb Switcher, Reaching Points, Water and Jug Problem.

Is there a brute force solution for Consecutive Numbers Sum?

Yes. Brute force (try every starting number) takes O(n log n) time and O(1) space. Try every possible first number of the run.

Which edge cases should I test for Consecutive Numbers Sum?

n = 1: only the number 1 itself, so the answer is 1; n is a power of two (2, 4, 8, ..., 2^29): no run of two or more numbers works, so the answer is 1; n is an odd prime: n itself and the pair (n - 1) / 2 + (n + 1) / 2, so the answer is 2; The single number n always counts as a run of length one, so the answer is never 0; Runs must use positive integers: allowing 0 or negative numbers would add extra, invalid runs; n up to 10^9 rules out trying every starting number; even k (k + 1) / 2 is safest computed in a long.