实验一 算法设计验证
1.求1~n的连续整数和。(逐个累加法和高斯法)
#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)
{
long sum;
clock_t t;
t=clock();
sum = add1(n);
t=clock()-t;
printf("逐个累加法\n");
printf("结果为:%ld\n",sum);
printf("共用时 %lf 秒\n",((float)t)/CLOCKS_PER_SEC);
}
/*-----------------高斯法----------------------------*/
long add2(long n)
{
return n*(n+1)/2;
}
void AddTime2(long n)
{
long sum;
clock_t t;
t=clock();
sum = add1(n);
t=clock()-t;
printf("高斯法\n");
printf("结果为:%ld\n",sum);
printf("共用时 %lf 秒\n",((float)t)/CLOCKS_PER_SEC);
}
int main(void)
{
int n;
printf("请输入数据n(n>1000000)\n");
scanf("%d",&n);
if(n<=1000000){
return 1;
}
AddTime1(n);
AddTime2(n);
return 0;
}
2.常见算法时间函数的增长情况。
#include <stdio.h>
#include <math.h>
double log2(double x) //求log2(x)
{
return log10(x)/log10(2);
}
long exponent(int n) //求2^n
{
long s=1;
for (int i=1;i<=n;i++)
s*=2;
return s;
}
long factorial(int n) //求n!
{
long s=1;
for (int i=1;i<=n;i++)
s*=i;
return s;
}
void fun(int n)
{
printf("log2(n) sqrt(n) n nlog2(n) n^2 n^3 2^n n!\n");
printf("===========================================================================\n");
for (int i=1;i<=n;i++)
{
printf("%5.2f\t",log2(double(i)));
printf("%5.2f\t",sqrt(i));
printf("%2d\t",i);
printf("%7.2f\t",i*log2(double(i)));
printf("%5d\t",i*i);
printf("%7d\t",i*i*i);
printf("%8d\t",exponent(i));
printf("%10d\n",factorial(i));
}
}
int main()
{
int n;
printf("请输入整数n\n");
scanf("%d",&n);
fun(n);
return 0;
}