Skip to content

829. Consecutive Numbers Sum

  • Time: $O(n)$
  • Space: $O(1)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
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;
  }
};
1
2
3
4
5
6
7
8
9
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;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
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