Consecutive Numbers Sum — LeetCode 829 Python Solution

HardMathEnumeration
Problem
#829
Reading time
2 min

The problem

Given an integer n, return the number of ways you can write n as the sum of consecutive positive integers.

Example

Input
n = 5
Output
2
Explanation
5 = 2 + 3

Python solution

Python
class Solution:
    def consecutiveNumbersSum(self, n: int) -> int:
        n <<= 1
        ans, k = 0, 1
        while k * (k + 1) <= n:
            if n % k == 0 and (n // k - k + 1) % 2 == 0:
                ans += 1
            k += 1
        return ans

Complexity

MeasureComplexity
TimeO(\sqrt{n}), where n is the given positive integer
SpaceO(1) auxiliary

Pattern: Math and Number Theory

Find the closed form, the invariant, or the modular identity — and skip the loop entirely. LeetCode 829. Consecutive Numbers Sum is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Math.

The math and number theory guide has the Python template for the pattern and the 485 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 829. Consecutive Numbers Sum?
LeetCode 829. Consecutive Numbers Sum is rated Hard on LeetCode.
What is the time complexity of LeetCode 829. Consecutive Numbers Sum?
The Python solution on this page runs in O(\sqrt{n}), where n is the given positive integer.
What is the space complexity of LeetCode 829. Consecutive Numbers Sum?
The Python solution on this page uses O(1) auxiliary space.
What topics does LeetCode 829. Consecutive Numbers Sum cover?
LeetCode 829. Consecutive Numbers Sum is tagged Math and Enumeration on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview