829. Consecutive Numbers Sum¶ Time: $O(n)$ Space: $O(1)$ C++JavaPython 1 2 3 4 5 6 7 8 9 10class 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 9class 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 11class 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