zoukankan      html  css  js  c++  java
  • Project Euler Problem 25 1000-digit Fibonacci number

    1000-digit Fibonacci number

    Problem 25

    The Fibonacci sequence is defined by the recurrence relation:

    Fn = Fn−1 + 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 index of the first term in the Fibonacci sequence to contain 1000 digits?


    C++:

    #include <iostream>
    #include <cstring>
    
    using namespace std;
    
    const int MAXN = 1000;
    
    char f1[MAXN+2], f2[MAXN+2];
    
    int fibadd(char f1[], char f2[], int digits)
    {
        int carry = 0, i;
        for(i=1; i<=digits || carry; i++) {
            f1[i] += f2[i] + carry;
            carry = f1[i] / 10;
            f1[i] %= 10;
        }
        return f1[i] ? i : i - 1;
    }
    
    int main()
    {
        int n, digits;
    
        while(cin >> n && n<= MAXN) {
            memset(f1, 0, sizeof(f1));
            memset(f2, 0, sizeof(f2));
    
            f1[1] = 1;
            f2[1] = 1;
            digits = 1;
    
            if(digits >= n) {
                cout << digits << endl;
            } else {
                for(int i=3;;) {
                    digits = fibadd(f1, f2, digits);
                    if(digits >= n) {
                        cout << i << endl;
                        break;
                    }
                    i++;
    
                    digits = fibadd(f2, f1, digits);
                    if(digits >= n) {
                        cout << i << endl;
                        break;
                    }
                    i++;
                }
            }
    
        }
    
        return 0;
    }




  • 相关阅读:
    java线程(1)-线程同步
    Scala:(3)数组
    Codeforces 899F Letters Removing
    拼图游戏的可解性
    Hash
    哈夫曼编码
    莫比乌斯
    FFT
    Ropes
    区间合并
  • 原文地址:https://www.cnblogs.com/tigerisland/p/7564010.html
Copyright © 2011-2022 走看看