//使用visual c++编写
1.求1~n的连续整数和
不同解法的绝对执行时间:add1(n)时间复杂度为O(n),add2(n)时间复杂度为O(1).
#include <stdio.h>
#include <time.h>
#include <math.h>
//-------------------方法一-------------
long add1(long n)
{
long i, sum = 0;
for(i=1; i<=n; i++)
sum += i;
return sum;
}
void AddTime1(long n)
{
clock_t t;
long sum;
t = clock();
sum = add1(n);
t = clock() - t;
printf("---方法一:\n");
printf("******结果: 1 ~ %d之和: %ld\n", n, sum);
printf("******用时: %lf 秒\n", ((float)t)/CLOCKS_PER_SEC);
}
//--------------------方法二---------------
long add2(long n)
{
return n*(n+1)/2;
}
void AddTime2(long n)
{
clock_t t;
long sum;
t = clock();
sum = add2(n);
t = clock() - t;
printf("---方法二:\n");
printf("******结果: 1 ~ %d之和: %ld\n", n, sum);
printf("******用时: %lf 秒\n", ((float)t)/CLOCKS_PER_SEC);
}
int main()
{
int n;
print