这是网易的一道面试题。
题目:输入一个正数n,输出所有和为n 连续正数序列。
例如输入15,由于1+2+3+4+5=4+5+6=7+8=15,所以输出3 个连续序列1-5、4-6 和7-8。
HANDWRITING:
想着用1 ~ i 的和偏移 j 个位置,即1+j + 2+j + …+ i+j = n ==> 1 + 2 +…+ i + i * j = n,开写
void search (int n) {
int sum = 1;
for (int i = 2; i < n; ++i) {
sum += i;
if (sum > n) break;
if ( (n-sum) % i != 0) continue;
int shift = (n-sum) / i;
cout<<1 + shift<<"-"<<i + shift<<endl;
}
}
ANSWER:
FROM:http://blog.csdn.net/v_july_v/article/details/6870251
It seems that this can be solved by factorization. However, factorization of large n is impractical!
Suppose n=i+(i+1)+...+(j-1)+j, then n = (i+j)(j-i+1)/2 = (j*j - i*i + i + j)/2
=> j^2 + j + (i-i^2-2n) = 0 => j=sqrt(i^2-i+1/4+2n) - 1/2
We know 1 <= i < j <= n/2 + 1
So for each i in [1, n/2], do this arithmetic to check if there is a integer answer.
int findConsecutiveSequence(int n) {
int count = 0;
for (int i=1; i<=n/2; i++) {
int sqroot = calcSqrt(4*i*i+8*n-4*i+1);
if (sqroot == -1) continue;
if ((sqroot & 1) == 1) {
System.out.println(i+”-” + ((sqroot-1)/2));
count ++;
}
}
return count;
}
Use binary search to calculate sqrt, or just use math functions.