Tony's Log

Algorithms, Distributed System, Machine Learning

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::

Since number could be 10^100, we have to use large number processing method, in string. A simpler method is to pre-calculate all Fibonacci numbers up to 101 digits, which is already fast enough.

//    536

#include <vector>
#include <iostream>
#include <string>
#include <cmath>
using namespace std;

vector<string> dict;

string plus_str(string &a, string &b)
{
    unsigned sizeA = a.length();
    unsigned sizeB = b.length();
    unsigned sizeDlt = (unsigned)abs(float(sizeA - sizeB));

    string &sL = sizeA > sizeB ? a : b;
    string &sS = !(sizeA > sizeB) ? a : b;


    unsigned sizeL = max(sizeA, sizeB);
    string ret(sizeL + 1, '0');

    int carry = 0;
    for(int i = sizeL - 1; i >= 0; i --)
    {
        int inxL = i;
        int inxS = i - sizeDlt;
        int inxR = i + 1;

        int dL = sL[inxL] - '0';
        int dS = inxS < 0 ? 0 : sS[inxS] - '0';

        int sum = dL + dS + carry;
        ret[inxR] = sum % 10 +'0';
        carry = sum >= 10 ? 1 : 0;
    }

    if(carry)
    {
        ret[0] = '1';
    }
    else
    {
        ret.erase(0, 1);
    }
    return ret;
}

//    1 : a > b
//    -1: a < b
//    0 : a == b
//
int comp(string &a, string &b)
{
    unsigned sza = a.size();
    unsigned szb = b.size();
    if(sza != szb) return sza > szb ? 1 : -1;

    // the same length
    for(unsigned i = 0; i < sza; i ++)
    {
        int da = a[i] - '0';
        int db = b[i] - '0';
        if(da != db)
        {
            return da > db ? 1 : -1;
        }
    }
    return 0;    // equal
}

void fill_fib(vector<string> &dict)
{
    dict.push_back("1");
    dict.push_back("2");

    bool bBreak = false;
    int i = 2;
    while(!bBreak)
    {
        string newFib = plus_str(dict[i - 1], dict[i - 2]);
        dict.push_back(newFib);
        bBreak = newFib.length() >= 101;
        i ++;
    }
}

int get_fib_cnt(string &a, string &b)
{
    int ret = 0;

    unsigned nSize = dict.size();
    for(int i = 0; i <nSize; i ++)
    {
        if(comp(dict[i], b) == 1) break;
        if(comp(dict[i], a) >= 0)
        {
            cout << "Found " << dict[i] << endl;
            ret ++;
        }
    }

    return ret;
}

int main()
{

    fill_fib(dict);

    string a, b;
    cin >> a >> b;

    while(!(a == "0" && b == "0"))
    {
        cout << get_fib_cnt(a, b) << endl;
        cin >> a >> b;
    }

    return 0;
}
View Code

I tried to find a closed form to Fibonacci only after I got a 0.01sec AC:
http://en.wikipedia.org/wiki/Fibonacci_number#Closed-form_expression

posted on 2014-02-10 14:43  Tonix  阅读(216)  评论(0编辑  收藏  举报