给出 n ,我们如何找到非负整数 a 和 b 使得 n = < em> a +( a +1)+( a +2)+…+ b 使用简单的C代码? / p>
这是我到目前为止所写的。
int main()
{
int a, b, n;
n=0;
printf("Enter the value of n:");
scanf("%d", &n);
n = a+(a+1)+(a+2)+b;
for(int i=a; i<=b; i++)
{
a=1;
b=8;
if (a<=i && i<=b)
printf("%d", i);
}
return 0;
}
答案 0 :(得分:3)
假设 n 和 a 不能为负:
#include <stdio.h>
/* n == a + (a+1) + (a+2) + ... + (a + m) == a*(m+1) + m*(m+1)/2
a = (n/(m+1)) - m/2;
b = (a + m) */
int main(void)
{
int n;
if ((scanf("%d", &n) != 1)|| (n < 0))
puts("invalid value");
else {
for (int m = 0; ; ++m) {
int a = (n/(m+1)) - m/2;
if (a < 0)
break;
/* check no round problem */
if ((a*(m+1) + m*(m+1)/2) == n)
printf("a=%d b=%d (m=%d)\n", a, a+m, m);
if (a == 0)
break;
}
}
return 0;
}
编译和执行:
pi@raspberrypi:/tmp $ gcc -pedantic -Wall -Wextra f.c
pi@raspberrypi:/tmp $ ./a.out
0
a=0 b=0 (m=0)
pi@raspberrypi:/tmp $ ./a.out
1
a=1 b=1 (m=0)
a=0 b=1 (m=1)
pi@raspberrypi:/tmp $ ./a.out
2
a=2 b=2 (m=0)
pi@raspberrypi:/tmp $ ./a.out
10
a=10 b=10 (m=0)
a=1 b=4 (m=3)
a=0 b=4 (m=4)
pi@raspberrypi:/tmp $ ./a.out
123
a=123 b=123 (m=0)
a=61 b=62 (m=1)
a=40 b=42 (m=2)
a=18 b=23 (m=5)
pi@raspberrypi:/tmp $
如果您不信任任何内容,则版本检查所有版本都是正确的;-)
#include <stdio.h>
/* n == a + (a+1) + (a+2) + ... + (a + m) == a*(m+1) + m*(m+1)/2
a = (n/(m+1)) - m/2;
a == 0 => n == m*(m+1)/2 =>
b = (a + m) */
int f(int a, int b)
{
int r = 0;
int m = 0;
do {
r += a+m;
} while ((a + m++) != b);
return r;
}
int main(void)
{
int n;
if ((scanf("%d", &n) != 1)|| (n < 0))
puts("invalid value");
else {
for (int m = 0; ; ++m) {
int a = (n/(m+1)) - m/2;
if (a < 0)
break;
if ((a*(m+1) + m*(m+1)/2) == n)
printf("a=%d b=%d (m=%d) : %s\n", a, a+m, m, (n == f(a, a+m)) ? "ok" : "KO");
if (a == 0)
break;
}
}
return 0;
}
编译和执行:
pi@raspberrypi:/tmp $ gcc -g -pedantic -Wall -Wextra f.c
pi@raspberrypi:/tmp $ ./a.out
0
a=0 b=0 (m=0) : ok
pi@raspberrypi:/tmp $ ./a.out
1
a=1 b=1 (m=0) : ok
a=0 b=1 (m=1) : ok
pi@raspberrypi:/tmp $ ./a.out
2
a=2 b=2 (m=0) : ok
pi@raspberrypi:/tmp $ ./a.out
10
a=10 b=10 (m=0) : ok
a=1 b=4 (m=3) : ok
a=0 b=4 (m=4) : ok
pi@raspberrypi:/tmp $ ./a.out
123
a=123 b=123 (m=0) : ok
a=61 b=62 (m=1) : ok
a=40 b=42 (m=2) : ok
a=18 b=23 (m=5) : ok
pi@raspberrypi:/tmp $
答案 1 :(得分:0)
解决此问题的一种可能方法是,不利用OP要求的已知算法进行算术级数公式化和“使用简单C代码”(嗯,对于 simple 的某些定义),是在探索a
和b
的可能值时使用连续的总计(或部分和)。
#include <stdio.h>
int main(void)
{
// Instead of asking a value 'n', test all the values up to 128
puts(" n a b\n-------------------");
for (int n = 0; n <= 128; ++n)
{
int a = 0;
int b = 0;
int sum = 0;
while ( a <= b && b <= n )
{
if ( sum == n )
{
printf("%5d%5d%5d\n", n, a, b);
}
if ( sum < n )
{
// Add the next highest term to the sum
++b;
sum += b;
}
else
{
// Remove the former lowest term from the sum
sum -= a;
++a;
}
}
}
}
可测试的HERE。