Consecutive Numbers Sum — LeetCode 829 Python Solution
HardMathEnumeration
- Problem
- #829
- Pattern
- Math and Number Theory
- Reading time
- 2 min
- Source
- leetcode.com
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 ansComplexity
| Measure | Complexity |
|---|---|
| Time | O(\sqrt{n}), where n is the given positive integer |
| Space | O(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.