题目大意:找到10组a和b,使得sum[1,a - 1] == sum[a, b]。
解题思路:先用二分做了一遍,枚举b,二分a,但是这样很慢,这能求出答案后把表输出来。
二分:
#include <stdio.h>
#include <string.h>
long long count(long long a, long long b) {
long long sum = (a + b) * (b - a + 1) / 2;
return sum;
}
bool search(int b) {
long long p, q;
int l = 0, r = b;
while (l < r) {
int mid = (l + r) / 2;
p = count(1, mid - 1), q = count(mid + 1, b);
if (p < q) l = mid;
else if (p > q) r = mid;
else {
printf("%10d%10d\n", mid, b);
return true;
}
if (l == r - 1) break;
}
return false;
}
int main () {
int cnt = 0;
for (int i = 4; cnt < 10; i++)
if (search(i)) cnt++;
return 0;
}
#include <stdio.h>
int x[] = {6, 35, 204, 1189, 6930, 40391, 235416, 1372105, 7997214, 46611179};
int y[] = {8, 49, 288, 1681, 9800, 57121, 332928, 1940449, 11309768, 65918161};
int main () {
for (int i = 0; i < 10; i++)
printf("%10d%10d\n", x[i], y[i]);
return 0;
}
现在有个数学公式,根据等差数列求和公式得到的,假设存在m和n满足上述条件,那么sum(1, m - 1 = (m - 1) * m / 2,
sum(m + 1, n) = (m + 1 + n) * (n - m) / 2, 两边相等化简得到n = ( sqrt(8 * m * m + 1) - 1) / 2.
#include <stdio.h>
#include <math.h>
int main() {
long long m = 1,c = 0;
double N;
while(c < 10) {
m++;
N = (sqrt(1.0 + 8 * m * m) - 1)/2;
if(N == floor(N)) {
printf("%10lld",m);
printf("%10.0lf\n",N);
c++;
}
}
return 0;
}