Problem
Given an integer <code>n</code>, return <em>the number of ways you can write </em><code>n</code><em> as the sum of consecutive positive integers.</em>Examples
Constraints
- 1 <= n <= 10^9
Documentation Index
Fetch the complete documentation index at: /llms.txt
Use this file to discover all available pages before exploring further.
Tested Python solution for LeetCode 829 with 22 pytest cases. Generate a practice environment with lcpy.
lcpy gen -n 829 # by problem number
lcpy gen -s consecutive_numbers_sum # by problem name
Input: n = 5
Output: 2
Input: n = 9
Output: 3
Input: n = 15
Output: 4
class Solution:
# Time: O(sqrt(n))
# Space: O(1)
def consecutive_numbers_sum(self, n: int) -> int:
count = 0
k = 1
while k * (k - 1) // 2 < n:
if (n - k * (k - 1) // 2) % k == 0:
count += 1
k += 1
return count
| Time | Space |
|---|---|
| O(sqrt(n)) | O(1) |