斐波那契数:前两个数为1,后面的数为它前两个数之和
递归法(速度慢)
#include<stdio.h> long long int Fib(int n) { if (n <= 2) return 1; else return Fib(n - 1) + Fib(n - 2); } int main() { int num = 0; scanf("%d", &num); printf("%lld\n",Fib(num)); return 0; }
递推法(速度更快)
#include<stdio.h> long long int Fib(int n) { int a = 1; int b = 1; int c = 1; while (n > 2) { c = a + b; a = b; b = c; n--; } return c; } int main() { int num=0; scanf("%d", &num); printf("%lld\n", Fib(num)); return 0; }
运行结果: