C言語再帰方法と非再帰写フィボナッチ数列
862 ワード
#include
int fib1(int);
int main(void){
int n;
printf("please input the index of fib:");
scanf("%d",&n);
printf("the %d fib1 number is %d
",n,fib1(n));
return 0;
}
int fib1(int n){
if(n<=0){
return 0;
}else if(n<=2){
return 1;
}else{
return fib1(n-1)+fib1(n-2);
}
}
次は非再帰法で書かれたフィボナッチ数列です
#include
int fib(int);
int main(void){
int n;
printf(" :
");
scanf("%d",&n);
printf("the %d fib number is %d
",n,fib(n));
return 0;
}
int fib(int n){
int i = 0;
int a = 1,b = 1;
int result;
if(n<=0){
return 0;
}else if(n<=2){
return 1;
}else{
for(i=3;i<=n;i++){
result = a+b;
a=b;
b= result;
}
return result;
}
}