斐波那契数 c 语言实现
斐波那契数列,又称黄金数列,指的是这样一个数列:1、1、2、3、5、8、13、21、……在数学上,斐波纳契数列以如下被以递归的方法定义:F(1)=1,F(2)=1,F(n)=F(n-1)+F(n-2)(n>2,n∈N*)。
第一种实现方法可以通过其定义得知:递归
int Fib2(int num) { int fib = 0; assert(num > 0); if(num < 3) fib = 1; else fib = Fib2(num - 1) + Fib2(num -2); return fib; }
第二种方法:迭代
int Fib1(int num) { int i = 1; int j = 1; int tmp = 1; int index = 0; assert(num > 0); for(index = 2;index < num; index++) { tmp = i + j; i = j; j = tmp; } return tmp; }
两种方法优劣,运行比较很容易得出
#include<stdio.h> #include<assert.h> int Fib1(int num) { int i = 1; int j = 1; int tmp = 1; int index = 0; assert(num > 0); for(index = 2;index < num; index++) { tmp = i + j; i = j; j = tmp; } return tmp; } int Fib2(int num) { int fib = 0; assert(num > 0); if(num < 3) fib = 1; else fib = Fib2(num - 1) + Fib2(num -2); return fib; } void displayFib(int num) { int i = 0; for(i = 1; i <= num; i++) { printf("%d ",Fib1(i)); } printf("%\n"); for(i = 1; i <= num; i++) { printf("%d ",Fib2(i)); } printf("\n"); } int main() { int num = 0; printf("please enter a unsinged int number(enter 0 quit):\n"); scanf("%d",&num); while(num) { displayFib(num); printf("please enter a unsinged int number(enter 0 quit):\n"); scanf("%d",&num); } return 0; }
whatever is worth doing is worth doing well...