project euler problem 25 大数连加Fibonacci序列

1000-digit Fibonacci number

Problem 25

The Fibonacci sequence is defined by the recurrence relation:

F n = F n1 + F n2, where F 1 = 1 and F 2 = 1.

Hence the first 12 terms will be:

F 1 = 1
F 2 = 1
F 3 = 2
F 4 = 3
F 5 = 5
F 6 = 8
F 7 = 13
F 8 = 21
F 9 = 34
F 10 = 55
F 11 = 89
F 12 = 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?


Answer:
4782
Completed on Wed, 9 Oct 2013, 16:36

这题算法类似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;
}


你可能感兴趣的:(project euler problem 25 大数连加Fibonacci序列)