1.4 算法与算法分析

同样计算1-1/x+1/x*x...

算法一 语句频度表达式为(1+n)*n/2,时间复杂度为T(n)=O(n*n)

算法二  语句频度表达式为n, 时间复杂度为T(n)=O(n)

算法一与算法二运行的结果是一样的,时间却差别很大。在算法正确的前提下,应该选择算法效率高的。

  

算法一:

/* algo1-1.c 计算1-1/x+1/x*x… */

#include<stdio.h>

#include<sys/timeb.h>

int main()

{

sturct  timeb t1,t2;

long t;

double x,sum=1,sum1;

int i,j,n;

printf("please input x n:");

scanf("%lf%d",&x,&n);

ftime(&t1);/* 求得当前时间 */

 for(i=1;i<=n;i++)
  {
     sum1=1;
     for(j=1;j<=i;j++)
       sum1=-sum1/x;
     sum+=sum1;
   }

   ftime(&t2); /* 求得当前时间 */
   t=(t2.time-t1.time)*1000+(t2.millitm-t1.millitm); /* 计算时间差 */
   printf("sum=%lf  use time%ldms\n",sum,t);
  }

}

[root@localhost algorithm]# gcc algo1-1.c -o algo1-1
[root@localhost algorithm]# ls
algo  algo1-1  algo1-1.c  algo1-2.c  Algo1-3.c
[root@localhost algorithm]# ./algo1-1 
please input x n:123 10000
sum=0.991935 use time230ms
[root@localhost algorithm]# 



算法二

 /* algo1-2.cpp 计算1-1/x+1/x*x…的更快捷的算法 */
 #include<stdio.h>
 #include<sys/timeb.h>
 void main()
 {
   struct timeb t1,t2;
   long t=0;
   double x,sum1=1,sum=1;
   int i,n;
   printf("请输入x n: ");
   scanf("%lf%d",&x,&n);
   ftime(&t1); /* 求得当前时间 */
   for(i=1;i<=n;i++)
   {
     sum1=-sum1/x;
     sum+=sum1;
   }

   ftime(&t2); /* 求得当前时间 */
   t=(t2.time-t1.time)*1000+(t2.millitm-t1.millitm); /* 计算时间差 */
   printf("sum=%lf 用时%ld毫秒\n",sum,t);
 }


[root@localhost algorithm]# ls
algo  algo1-1  algo1-1.c  algo1-2  algo1-2.c  Algo1-3.c
[root@localhost algorithm]# gcc algo1-2.c -o algo1-2
[root@localhost algorithm]# ./algo1-2
plesae inputx n: 123 10000
sum=0.991935 use time0ms
[root@localhost algorithm]# 

你可能感兴趣的:(1.4 算法与算法分析)