Fibbonacci Number
Time Limit: 1000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 38819 Accepted Submission(s): 17414
Problem Description
Your objective for this question is to develop a program which will generate a fibbonacci number. The fibbonacci function is defined as such:
f(0) = 0
f(1) = 1
f(n) = f(n-1) + f(n-2)
Your program should be able to handle values of n in the range 0 to 50.
Input
Each test case consists of one integer n in a single line where 0≤n≤50. The input is terminated by -1.
Output
Print out the answer in a single line for each test case.
Sample Input
3
4
5
-1
Sample Output
2
3
5
一开始天真的以为,这么简单???几下子就写完了,然后Wrong Answer,然后调试了一下,输出Fib(50),数据是负数,这才发现是数据溢出了,把Fib数组改成long long int 也解决不了问题。
我这体会到,数据真的太容易溢出了,然后想用字符串数组来存数的每一位就好了,在写的时候发现用整型数组不是更简单。最后花了一小时才写完,还调试了挺久才OK了(我这效率…),后面想到用三个一维整型数组不如直接用一个二维数组来得更清晰明了,还不用每次都重新计算(但是,其实各有各的优点了)。
至于二维数组的话,思路是一样的。我的具体解题思路在代码的注释部分写的比较详细,有需要的话欢迎去了解一下!
后续:查了一些别人的ac代码,发现用_INT64就行了。百度百科:Int64是有符号 64 位整数数据类型,相当于C++中的long long、 C# 中的 long 和 SQL Server 中的 bigint,表示值介于 -2^63 ( -9,223,372,036,854,775,808)
到2^63-1(+9,223,372,036,854,775,807 )之间的整数。
那就奇怪了,我一开始用了long long ,不能过。。。。。。嗯,试了一下,这次long long int ,AC了,那我当时第一次试的时候发生了什么?阿西,我忘了,嗯管它了,综上,这题没必要像我这么麻烦,直接用long long定义整型数组就能AC了!!!
#include
using namespace std;
const int maxn = 50; //上限50位就够,用整型数组存大数
//整型数组里倒过来存数的每一位,例如:{0,0,1,2,3,0,0...} 表示32100
int operate(int *f0, int *f1, int *fib) {
int carry = 0; //初始化进位位为0
for (int i = 0; ; i++) {
int term = (f0[i] + f1[i] + carry) % 10; //本位
carry = (f0[i] + f1[i] + carry) / 10; //进位
fib[i] = term;
if (f0[i+1] == 0 && f1[i+1] == 0 && carry == 0) break;
}
//更新一下f0、f1
for (int i = 0; i < maxn; i++) {
f0[i] = f1[i];
}
for (int i = 0; i < maxn; i++) {
f1[i] = fib[i];
}
return 0;
}
int main() {
int n;
while (cin >> n && n != -1) {
if (n == 0) {
cout << 0 << endl;
continue;
}
if (n == 1) {
cout << 1 << endl;
continue;
}
int f0[maxn] = {0,0,0}; //初始化第一个数
int f1[maxn] = {1,0,0}; //初始化第二个数
int fib[maxn] = {0,0,0}; //注意,空闲位全置为0,作为标记
for (int i = 2; i <= n; i++) {
operate(f0,f1,fib);
}
//打印出结果
for (int i = maxn - 1; i >= 0; i-- ) {
if (fib[i] != 0) {
for ( ;i >= 0 ;i-- ) cout << fib[i];
cout << endl;
break;
}
// cout << fib[i];
}
// cout << endl;
}
return 0;
}