1 /** 2 给定斐波那契数列的项数求对应的数值 3 参考:剑指Offer 4 */ 5 #include <stdio.h> 6 7 int fib(int n); 8 long long fibonacci(unsigned int n); 9 int main(int argc, const char * argv[]) { 10 11 int n; 12 13 while (1) { 14 15 printf("请输入你想知道到的斐波那契数列的项数:\t"); 16 scanf("%d",&n); 17 int result = fib(n); 18 long long googResult = fibonacci(n); 19 printf("与之对应的斐波那契数列数列的值为:\t%d\t%lld\n\n",result,googResult); 20 21 22 } 23 return 0; 24 } 25 26 27 int fib(int n){ 28 29 if(n == 0){ 30 return 0; 31 }else if(n == 1){ 32 return 1; 33 }else { 34 return fib(n-1) + fib(n-2); 35 } 36 37 } 38 39 //斐波那契数列数列求解优化 40 41 long long fibonacci(unsigned int n){ 42 43 int result[] = {0,1}; 44 if (n < 2){ 45 return result[n]; 46 } 47 long long smallest = 0; 48 long long smaller = 1; 49 long long temp = 0; 50 51 for(int i=2; i<=n; i++){ 52 53 temp = smaller + smallest; 54 55 smallest = smaller; 56 smaller = temp; 57 58 } 59 return temp; 60 61 }
时间: 2024-10-14 22:46:12