编写一个程序exp-1.c。对于给定的正整数n,求1+2+……n,采用逐个累加和n(n+1)/2高斯法两种解法。对于相同的n,给出两种解法的求和结果和求解时间并用数据进行测试。
时间: 2024-02-12 07:03:40 浏览: 62
好的,以下是exp-1.c的示例代码:
```c
#include <stdio.h>
#include <time.h>
// 逐个累加求和
int sum1(int n) {
int s = 0;
for (int i = 1; i <= n; i++) {
s += i;
}
return s;
}
// 高斯求和公式
int sum2(int n) {
return n * (n + 1) / 2;
}
int main() {
int n = 1000000000;
clock_t start, end;
double duration;
// 逐个累加求和
start = clock();
int s1 = sum1(n);
end = clock();
duration = (double)(end - start) / CLOCKS_PER_SEC;
printf("逐个累加求和结果:%d,求解时间:%f秒\n", s1, duration);
// 高斯求和公式
start = clock();
int s2 = sum2(n);
end = clock();
duration = (double)(end - start) / CLOCKS_PER_SEC;
printf("高斯求和公式结果:%d,求解时间:%f秒\n", s2, duration);
return 0;
}
```
这个程序中我们定义了两个函数,`sum1`和`sum2`分别是逐个累加求和和高斯求和公式的函数。在`main`函数中,我们先设定一个正整数n,然后分别调用这两个函数,并计算它们的求解时间。最后输出两种方法的求和结果和求解时间。
你可以根据自己的需要修改n的值,测试程序的运行时间和结果。
阅读全文