hdoj1715-大菲波數

題目鏈接

Problem Description

Fibonacci數列,定義如下:
f(1)=f(2)=1
f(n)=f(n-1)+f(n-2) n>=3。
計算第n項Fibonacci數值。

Input

輸入第一行爲一個整數N,接下來N行爲整數Pi(1<=Pi<=1000)。

Output

輸出爲N行,每行爲對應的f(Pi)。

Sample Input

5
1
2
3
4
5

Sample Output

1
1
2
3
5

思路

此題就是大數的運算,我設置了一個二維數組來儲存結果,爲了減少運算次數,我每次將四位放在一起進行運算;如下圖:
這裏寫圖片描述
上面是9999+9999的運算,因爲個數組元素儲存的四位數,當出現上述結果時就得進“1”,也就是將比當前運算的位數的更高一位加一;因爲我是用的int數組,int類型的最大取值爲5位數,因此我們每次只能進行四位數的運算,否則會出現溢出,如果想每次計算更多位,可以採用long long型數組儲存結果;

code

#include <iostream>
#include <iomanip>
#include <cstring>

using namespace std;

const int B = 10000;
const int M = 1000+5;

int fi[M][60];

void add(int n)
{
    int loc = 0;
    while(fi[n-1][loc] != 0 || fi[n-2][loc] != 0)
    {
        int temp = fi[n-1][loc] + fi[n-2][loc];
        if(temp >= B)
        {
            fi[n][loc] += temp % B;
            fi[n][loc+1] += 1;
        }
        else
        {
            fi[n][loc] += temp;
        }
        loc ++;
    }
}

int main()
{
    memset(fi, 0, sizeof(fi));
    fi[1][0] = fi[2][0] = 1;
    for(int i = 3; i < M; i ++)
    {
        add(i);
    }
    int n;
    cin >> n;
    while(n --)
    {
        int p;
        cin >> p;
        int loc = 59;
        while(fi[p][loc] == 0)
        {
            loc --; //找出最高位
        }
        cout << fi[p][loc];
        for(int i = loc-1; i >= 0; i --)
        {
            cout << setw(4) <<setfill('0') << fi[p][i];
        }
        cout << endl;
    }
    return 0;
}
發佈了60 篇原創文章 · 獲贊 7 · 訪問量 2萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章