#include <stdio.h>
#include <time.h>
#include <math.h>
/*------------------------方法1--------------------------*/
long add1(long n)
{
long i, sum = 0;
for(i = 1; i <= n; i++)
sum += i;
return sum;
}
void add_time1(long n)
{
long sum;
clock_t t;
t = clock();
sum = add1(n);
t = clock() - t;
printf("方法1:\n");
printf(" 结果:1~%d之和:%ld\n", n, sum);
printf(" 用时:%lf秒\n",((float)t)/CLOCKS_PER_SEC);
}
/*------------------------方法2--------------------------*/
long add2(long n)
{
return n * (n + 1) / 2;
}
void add_time2(long n)
{
long sum;
clock_t t;
t = clock();
sum = add2(n);
t = clock() - t;
printf("方法2:\n");
printf(" 结果:1~%d之和:%ld\n", n, sum);
printf(" 用时:%lf秒\n",((float)t)/CLOCKS_PER_SEC);
}
int main(void)
{
int n;
printf("n(大于1000000):");
scanf("%d", &n);
if(n < 1000000)
return 0;
add_time1(n);
add_time2(n);
return 0;
}
结果:
./test
n(大于1000000):99999999
方法1:
结果:1~99999999之和:4999999950000000
用时:0.398908秒
方法2:
结果:1~99999999之和:4999999950000000
用时:0.000000秒