题目地址:
https://www.lintcode.com/problem/consecutive-numbers-sum/description
给一个数字 ,问有多少种方法可以将其写成连续的若干正整数之和。
设 ,解得 其中 为首项, 为项数。所以我们只需要从 开始枚举 即可。显然 越大则解出来的 越小,当解出小于 的 时循环就终止。代码如下:
public class Solution {
/**
* @param N: an integer
* @return: how many ways can we write it as a sum of consecutive positive integers
*/
public int consecutiveNumbersSum(int N) {
// Write your code here
int res = 0, count = 1;
double a = 1, num = (double) N;
// 如果解出的首项小于1了,那就枚举结束
while (a >= 1) {
// 解出首项
a = num / count - (count - 1) / 2.0;
// 如果首项是个正整数则计答案 + 1
if (isInteger(a) && a >= 1) {
res++;
}
// 枚举项数 + 1
count++;
}
return res;
}
private boolean isInteger(double a) {
return Math.abs(a - (int) a) <= 1E-10;
}
}
时间复杂度 ,只需注意到不等式 ,推出 ,然后即得结论。