1. 题目描述
Fibonacci数列定义为:
A0 = 0, A1 = 1;
An = An-1 + An-2, if n >= 2.
问题:输入一个n( 0 ≤ n ≤ 40 ),计算An.
2. 算法设计
直接利用公式计算即可,时间复杂度O(N),由于数据规模很小,可以选择
- 先打表,然后对每一个测试数据n,直接输出An;
- 或者分别对每一个n,计算An。
3. AC Code
1 #include <stdio.h> 2 #define N 41 3 int f[N]; 4 void pre_do(); 5 void ac_fun(); 6 int main() 7 { 8 //freopen("in.txt", "r", stdin); 9 pre_do(); 10 ac_fun(); 11 return 0; 12 } 13 void pre_do() 14 { 15 int i; 16 f[0] = 0; f[1] = 1; 17 for (i = 2;i < N;i++) f[i] = f[i-1] + f[i-2]; 18 } 19 void ac_fun() 20 { 21 int n; 22 while(scanf("%d", &n) != EOF) 23 { 24 printf("The Fibonacci number for %d is %d\n", n, f[n]); 25 } 26 }
时间: 2024-08-10 21:15:01