1,1,2,3,5,8,13...这样前两个数相加等于第三个数的数列叫做斐波那契数列
输入:x
输出:斐波那契的第x个数
-
递归-效率低
#include<stdio.h>
int count = 0;
int Febo(int m) {
if (m == 3)
count++;//统计计算中3的出现次数
if (m > 2)
return Febo(m - 2) + Febo(m - 1);
else
return 1;
}
int main() {
int x;
scanf("%d", &x);
printf("%d\n", Febo(x));
printf("%d", count);
}
-
迭代-效率高
#include<stdio.h>
int Febo(int m) {
int a = 1;
int b = 1;
int c = 1;
while (m>2) {
c = a + b;
a = b;
b = c;
m--;
}
return c;
}
int main() {
int x;
scanf("%d", &x);
Febo(x);
printf("%d", Febo(x));
}