HardNo. 0829

Consecutive Numbers Sum — LeetCode 829 Python Solution

Topics
Math, Enumeration
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

PythonSolution
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

Time
O(√n), where n is the given positive integer
Space · auxiliary
O(1)

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

Related problems
No.ProblemDifficulty
0180Consecutive NumbersMedium
0204Count PrimesMedium
0479Largest Palindrome ProductHard
0906Super PalindromesHard
1925Count Square Sum TriplesEasy
1952Three DivisorsEasy

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(√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.

Free to download. Check it runs on your machine, then pick a plan.