1000-digit Fibonacci number
Problem 25
The Fibonacci sequence is defined by the recurrence relation:
Fn = Fn1 + Fn
2, where F1 = 1 and F2 = 1.
Hence the first 12 terms will be:
F1 = 1
F2 = 1
F3 = 2
F4 = 3
F5 = 5
F6 = 8
F7 = 13
F8 = 21
F9 = 34
F10 = 55
F11 = 89
F12 = 144
The 12th term, F12, is the first term to contain three digits.
What is the first term in the Fibonacci sequence to contain 1000 digits?
这题算法类似POJ 1503,稍加改动就行了,容易。
#include <iostream>
#include <map>
#include <string>
#include <cstring>
#include <cstdio>
#include <cmath>
#include <algorithm>
using namespace std;
#include<iostream>
#include<cstring>
char a[1010],b[1010];
using namespace std;
int main()
{
int k=0,abc=2; //前面有两个数了,故abc=2
cin>>a>>b; //输入第一第二个数即输入:1 1
while(k!=1000)
{
int i,j,p,q,c[2000]= {0};
p=strlen(a);
q=strlen(b);
for(i=p-1,j=p; i>=0; i--)
{
if(i-p+q>=0) c[j]+=(a[i]-48)+(b[i-p+q]-48); //模拟加法运算
else c[j]+=(a[i]-48);
if(c[j]>9)
{
c[j-1]+=1;
c[j]-=10;
}
j--;
}
strcpy(b,a); //b字符串就取当前的a字符串
for(i=0; i<=p; i++)
{
if(c[i]!=0)
{
int m=0;
for(; i<=p; i++)
a[m++]=c[i]+'0'; //a字符串更新为当前结果
a[m]='\0';
}
}
k=strlen(a); //这两个数相加的结果的位数
abc++;
}
cout<<abc<<endl;
return 0;
}