一.递归算法
#define _CRT_SECURE_NO_WARNINGS 1
#include<stdio.h>
int fib(int k)
{if (k <= 2)return 1;elsereturn fib(k - 1) + fib(k - 2);
}
int main()
{int n = 0;int res = 0;printf("求输入斐波那契数列的阶数");scanf("%d", &n);res=fib(n);printf("%d\n", res);return 0;
}
很明显该算法时间复杂度比较大,想要求出k阶斐波那契数列要先求出k-1阶斐波那契数列和k-2阶斐波那契数列
2.循环算法
#define _CRT_SECURE_NO_WARNINGS 1
#include<stdio.h>
int fib(int k)
{int a = 1;int b = 1;//a,b均为下标int c = 1;while (k >= 3){c = a + b;a = b;b = c;k--;}return c;
}
int main()
{int n = 0;int res = 0;printf("求输入斐波那契数列的阶数");scanf("%d", &n);res = fib(n);printf("%d\n", res);return 0;
}
注意:求斐波那契额数列要考虑溢出,int范围:
-32678–+32767