829. Consecutive Numbers Sum
Difficulty: Medium
Given a positive integer N
, how many ways can we write it as a sum of consecutive positive integers?
Example 1:
1 | Input: 5 |
Example 2:
1 | Input: 9 |
Example 3:
1 | Input: 15 |
Solution
根据题目,我们可以有
1 | N = (x+1)+(x+2)+...+(x+k) = 1/2 * ((x+1)+(x+k))*k |
于是我们可以得到
1 | 2*x = 2*N/k - (k + 1) // Note: 2*x是整数,(k+1)也是整数,所有(2*N/k)也应该是整数 |
因为x为非负数,所以上述等式右边肯定大于0
1 | 2*N/k - k - 1 >= 0 |
Language: Java
1 | class Solution { |