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

  1. Problem Statement
  2. Complexity Analysis
  3. Consecutive Numbers Sum solution in C++
  4. Consecutive Numbers Sum solution in Java
  5. Consecutive Numbers Sum solution in Python
  6. Additional Resources
829. Consecutive Numbers Sum LeetCode Solution image

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

See also  1073. Adding Two Negabinary Numbers LeetCode Solution

Happy Coding! Keep following PROGIEZ for more updates and solutions.