首页 > 代码库 > 算法时间复杂度对比

算法时间复杂度对比

题目:求1-1/x+1/x^2-1/x^3+......+1/(-x)^(n-1)

算法一:

 

#include<stdio.h>#include<sys/timeb.h>void main(){    timeb t1,t2;    long t;    double x,sum=1,sum1;    int i,j,n;    printf("请输入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*(-1.0/x);        sum+=sum1;    }    ftime(&t2);    t=(t2.time-t1.time)*1000+(t2.millitm-t1.millitm);    printf("sum=%lf用时%ld毫秒\n",sum,t);}

时间复杂度:

算法2:

#include<stdio.h>#include<sys/timeb.h>void main(){    timeb t1,t2;    long t;    double x,sum=1,sum1=1;    int i,j,n;    printf("请输入x n:");    scanf("%lf%d",&x,&n);    ftime(&t1);    for (i=1;i<=n;i++)    {        sum1*=(-1.0/x);        sum+=sum1;    }    ftime(&t2);    t=(t2.time-t1.time)*1000+(t2.millitm-t1.millitm);    printf("sum=%lf用时%ld毫秒\n",sum,t);}

时间复杂度: