#include <stdio.h>
#include <math.h>
#include <time.h>
#define MAXK 1e6
/*
You can get the question Frome:\project\java_algorithm\c_algorithem\algorithm01\week01\compareforandrecursion Demo2.bmp
or from web:http://www.icourse163.org/learn/zju-93001?tid=1002019005#/learn/content?type=detail&id= 1002635001&cid=1002891006
*/
/*
Implement this question using violence loop
The T (n) =o (n^2);
*/
Double fun1 (double x,int n) {
Double sum=1.0;
int i;
for (i=1;i<=100;i++) {
Sum+=pow (x,i)/I;
}
return sum;
}
/*
We can store x^i into a temp, every time
We only need to multiply I base on last time value.
T (n) =2n
*/
Double fun2 (double x,int n) {
Double sum=1.0;
Double temp=1;
int i;
for (i=1;i<100;i++) {
Temp=temp*x;
sum=sum+temp/i;
}
return sum;
}
/*just A Main method used to test*/
void Main () {
int i;
Start the Time,use the second
clock_t Start,end;
Double duration;//used to Stored Top-end
Start=clock ();
for (i=0;i<maxk;i++) {
FUN1 (1.1,100);
}
End=clock ();
Duration= (Double) (End-start))/clk_tck/maxk;
printf ("Every method fun1 using Average time:%f\n", duration);
Start=clock ();
for (i=0;i<maxk;i++) {
Fun2 (1.1,100);
}
End=clock ();
Duration= (Double) (End-start))/clk_tck/maxk;
printf ("Every method fun2 using Average time:%f\n", duration);
/*
Summary:sometimes,you can using temporary variable to reduce the T (n)
*/
}
Comparison of algorithms for solving n-order polynomial