Title address:
https://www.lintcode.com/problem/consecutive-numbers-sum/description
Give a number , ask how many methods can be written as the sum of consecutive positive integers.
Assume ,Solutions have to among them first item, is the number of items. So we just need to Start enumeration enough. Obviously greater the , the better smaller a is, when the solution is less than of , the loop is terminated. code show as below:
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;
}
}
time complexity , Just notice the inequality , launch , and then a conclusion is drawn.