大菲波数
Time Limit: 1000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)Total Submission(s): 20440 Accepted Submission(s): 6897
Problem Description
Fibonacci数列,定义如下:
f(1)=f(2)=1
f(n)=f(n-1)+f(n-2) n>=3。
计算第n项Fibonacci数值。
f(1)=f(2)=1
f(n)=f(n-1)+f(n-2) n>=3。
计算第n项Fibonacci数值。
Input
输入第一行为一个整数N,接下来N行为整数Pi(1<=Pi<=1000)。
Output
输出为N行,每行为对应的f(Pi)。
Sample Input
5 1 2 3 4 5
Sample Output
1 1 2 3 5
Source
#include<stdio.h>
#include<iostream>
#include<algorithm>
using namespace std;
#define size 1010
char fib[size][300];
void add(char s1[],char s2[],int now) {
int i, j, k, n, m;
int a[size], b[size], c[size];
memset(a, 0, sizeof(a));
memset(b, 0, sizeof(b));
memset(c, 0, sizeof(c));
n = strlen(s1);
m = strlen(s2);
for (i = 0; i<n; i++)
a[i] = s1[n - i - 1] - '0';
for (i = 0; i<m; i++)
b[i] = s2[m - i - 1] - '0';
if (n>m)
k = n;
else
k = m;
/*加运算*/
for (i = 0; i <= k; i++) {
c[i] += a[i] + b[i];
if (c[i]>9) {
c[i + 1]++;
c[i] %= 10;
}
}
/*去除前导0*/
i = k;
while (c[i] == 0) i--;
/*判断两个非负数之和是否为0,以及逆序打印c[]*/
int index = 0;
while (i >= 0) {
fib[now][index] = c[i] + 48;
index++;
i--;
}
fib[now][index] = 0;
}
void fibnacci() {
fib[1][0] = '1';
fib[2][0] = '1';
for (int i = 3; i < size; i++) {
add(fib[i - 1], fib[i - 2], i);
}
}
int main() {
int test, n;
fibnacci();
scanf("%d", &test);
while (test--) {
scanf("%d", &n);
printf("%s\n", fib[n]);
}
}