1 Fibonacci implemented by Loop
#include <stdlib.h>
#include <stdio.h>
int fib(int n)
{
if(n == 1 || n == 2){
return 1;
}
int f1 = 1;
int f2 = 1;
int f3;
int i;
for(i=3; i<= n; i++){
f3 = f1 + f2;
f1 = f2;
f2 = f3;
}
return f3;
}
int main(int argc, char** argv)
{
int N = atoi(argv[1]);
printf("%d\n", fib(N));
return 0;
}
2 Fibonacci implemented by Recursion
#include <stdio.h>
#include <stdlib.h>
int fib(int n)
{
if(n==1 || n == 2){
return 1;
}
return fib(n-1) + fib(n-2);
}
int main(int argc, char** argv)
{
int N = atoi(argv[1]);
printf("%d\n", fib(N));
return 0;
}
3 Performence comparision
$ time ./fib_loop 40
102334155
real 0m0.001s
user 0m0.001s
sys 0m0.000s
$ time ./fib_recursion 40
102334155
real 0m0.134s
user 0m0.134s
sys 0m0.000s
No comments:
Post a Comment