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;
    }




  • 相关阅读:
    redis集群
    鉴权方案选择
    spring mvc 自定义handler不拦截静态资源
    servlet3
    压测工具 ab jmeter
    死锁产生的原因
    缓存方案:本地guavaCache, 远程redis?
    使用spring boot admin
    groovy使用小记
    python--面试题01
  • 原文地址:https://www.cnblogs.com/tigerisland/p/7564010.html
Copyright © 2011-2022 走看看