The Fibonacci sequence is defined by the recurrence relation:
F n = F n−1 + F n−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 index of the first term in the Fibonacci sequence to contain 1000 digits?
#include<iostream>
#include<string.h>
using namespace std;
int a[1005],b[1005];
void add(int a[],int b[]){
int c;
for(int i = 1;i <= 1000;i++){
c = a[i];
a[i] += b[i];
b[i] = c;
}
for(int j = 1;j <=1000; j++){
if(a[j]>=10){
a[j+1]++;
a[j] %= 10;
}
}
}
int main()
{
memset(a,0,sizeof(a));
memset(b,0,sizeof(b));
int temp = 2;
a[1] = 1;
b[1] = 1;
while(!a[1000]){
temp++;
add(a,b);
}
for(int i=0;i<50;i++){
cout<<a[i];
}
cout<<endl;
for(int i=0;i<50;i++){
cout<<b[i];
}
cout<<endl;
cout<<temp<<endl;
return 0;
}
更新一下做法,系统的写一写:
#include <iostream>
#include <algorithm>
#include <string.h>
#include <cmath>
using namespace std;
int f[2][1005];
int main() {
int n = 2;
f[1][0] =f[1][0] = f[0][1] = f[1][1] = 1;
while ( f[n%2][0] < 1000 ) {
n++;
/*n0存的是当前位,n1存的是边上的n-1位,n0位没有n1位大*/
int n1= !(n & 1);
int n0 = n1 ^ 1;
int len;
f[n0][0] > f[n1][0] ? len = f[n0][0]:len = f[n1][0];
for (int i = 1; i <= len; i++) {
f[n0][i] += f[n1][i];
}
f[n0][0] = len;
for (int i = 1; i <= f[n0][0]; i++) {
if(f[n0][i] < 10) continue;
f[n0][i+1] += f[n0][i]/10;
f[n0][i] %= 10;
f[n0][0] += (f[n0][0] == i);
}
}
cout << n << endl;
return 0;
}