> ## Documentation Index
> Fetch the complete documentation index at: https://leetcode-py.wisl.dev/llms.txt
> Use this file to discover all available pages before exploring further.

> ## Agent Instructions
> leetcode-py is a Python LeetCode practice environment generator with one CLI: lcpy. It is not a service or platform.
> Each problem is a directory under leetcode/ with README.md, solution.py, test_solution.py, helpers.py, and playground.ipynb. lcpy gen creates them from JSON templates bundled with the package.
> Examples are backed by tests; copy them verbatim.

# Consecutive Numbers Sum Python Solution

> Tested Python solution for LeetCode 829 with 22 pytest cases. Generate a practice environment with lcpy.

LeetCode 829, [Hard](/catalog/hard). Topics: [Math](/catalog/topics/math), [Enumeration](/catalog/topics/enumeration). [View on LeetCode](https://leetcode.com/problems/consecutive-numbers-sum/description/).

Generate this problem as a practice environment: tested reference solution, 22 [parametrized pytest cases](/practice/testing), and a playground notebook:

```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
lcpy gen -n 829   # by problem number
lcpy gen -s consecutive_numbers_sum   # by problem name
```

## 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

```
Input: n = 5
Output: 2
```

**Explanation:** 5 = 2 + 3

```
Input: n = 9
Output: 3
```

**Explanation:** 9 = 4 + 5 = 2 + 3 + 4

```
Input: n = 15
Output: 4
```

**Explanation:** 15 = 8 + 7 = 4 + 5 + 6 = 1 + 2 + 3 + 4 + 5

### Constraints

* 1 \<= n \<= 10^9

## Solution

Reference implementation from [solution.py on GitHub](https://github.com/wislertt/leetcode-py/blob/main/leetcode/consecutive_numbers_sum/solution.py), full suite in [test\_solution.py](https://github.com/wislertt/leetcode-py/blob/main/leetcode/consecutive_numbers_sum/test_solution.py):

```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
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
```

## Complexity

| Time | Space |
| - | - |
| O(sqrt(n)) | O(1) |

## Tags


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.