829. Consecutive Numbers Sum LeetCode Solution
In this guide, you will get 829. Consecutive Numbers Sum LeetCode Solution with the best time and space complexity. The solution to Consecutive Numbers Sum problem is provided in various programming languages like C++, Java, and Python. This will be helpful for you if you are preparing for placements, hackathons, interviews, or practice purposes. The solutions provided here are very easy to follow and include detailed explanations.
Table of Contents
- Problem Statement
- Complexity Analysis
- Consecutive Numbers Sum solution in C++
- Consecutive Numbers Sum solution in Java
- Consecutive Numbers Sum solution in Python
- Additional Resources

Problem Statement of Consecutive Numbers Sum
Given an integer n, return the number of ways you can write n as the sum of consecutive positive integers.
Example 1:
Input: n = 5
Output: 2
Explanation: 5 = 2 + 3
Example 2:
Input: n = 9
Output: 3
Explanation: 9 = 4 + 5 = 2 + 3 + 4
Example 3:
Input: n = 15
Output: 4
Explanation: 15 = 8 + 7 = 4 + 5 + 6 = 1 + 2 + 3 + 4 + 5
Constraints:
1 <= n <= 109
Complexity Analysis
- Time Complexity: O(n)
- Space Complexity: O(1)
829. Consecutive Numbers Sum LeetCode Solution in C++
class Solution {
public:
int consecutiveNumbersSum(int n) {
int ans = 0;
for (int i = 1, triangleNum = i; triangleNum <= n; ++i, triangleNum += i)
if ((n - triangleNum) % i == 0)
++ans;
return ans;
}
};
/* code provided by PROGIEZ */
829. Consecutive Numbers Sum LeetCode Solution in Java
class Solution {
public int consecutiveNumbersSum(int n) {
int ans = 0;
for (int i = 1, triangleNum = i; triangleNum <= n; ++i, triangleNum += i)
if ((n - triangleNum) % i == 0)
++ans;
return ans;
}
}
// code provided by PROGIEZ
829. Consecutive Numbers Sum LeetCode Solution in Python
class Solution:
def consecutiveNumbersSum(self, n: int) -> int:
ans = 0
i = 1
triangleNum = 1
while triangleNum <= n:
if (n - triangleNum) % i == 0:
ans += 1
i += 1
triangleNum += i
return ans
# code by PROGIEZ
Additional Resources
- Explore all LeetCode problem solutions at Progiez here
- Explore all problems on LeetCode website here
Happy Coding! Keep following PROGIEZ for more updates and solutions.