# 829. Consecutive Numbers Sum

Given a positive integer `N`, how many ways can we write it as a sum of consecutive positive integers?

Example 1:

``````Input: 5
Output: 2
Explanation: 5 = 5 = 2 + 3
``````

Example 2:

``````Input: 9
Output: 3
Explanation: 9 = 9 = 4 + 5 = 2 + 3 + 4
``````

Example 3:

``````Input: 15
Output: 4
Explanation: 15 = 15 = 8 + 7 = 4 + 5 + 6 = 1 + 2 + 3 + 4 + 5
``````

Note: `1 <= N <= 10 ^ 9`.

``````x, x+1, x+2, ..., x+k-1
``````

``````kx + (k-1)k / 2 = N
``````

``````kx = N - (k-1)k / 2
``````

``````N - (k-1)k / 2 > 0
``````

``````k < sqrt(2N)
``````

``````class Solution {
public:
int res = 1;
for (int i = 2; i < sqrt(2 * N); ++i) {
if ((N - i * (i - 1) / 2) % i == 0) ++res;
}
return res;
}
};
``````

``````class Solution {
public:
int res = 0, sum = 0;
for (int i = 1; sum < N; ++i) {
sum += i;
if ((N - sum) % i == 0) ++res;
}
return res;
}
};
``````

Github 同步地址:

https://github.com/grandyang/leetcode/issues/829

https://leetcode.com/problems/consecutive-numbers-sum/

https://leetcode.com/problems/consecutive-numbers-sum/discuss/129227/JAVA-easy-4-lines-O(n0.5)

https://leetcode.com/problems/consecutive-numbers-sum/discuss/128959/5-line-O(N-0.5)-Java-code-Math-method

https://leetcode.com/problems/consecutive-numbers-sum/discuss/129015/5-lines-C%2B%2B-solution-with-detailed-mathematical-explanation.

 微信打赏 Venmo 打赏
（欢迎加入博主的知识星球，博主将及时答疑解惑，并分享刷题经验与总结，试运营期间前五十位可享受半价优惠～）

×

Help us with donation