2012-02-25 12 views
0

数式から計算された数値を格納する配列を作成し、メモリに配置しようとしています。したがって、後で番号が再度呼び出されると、再計算する必要はありません。そのメモリ内に既に存在します。計算された数値をメモリに格納する配列を作成します。

式が

fib(n-1) + fib(n-2); 

あなたはそれを保存することができますように、与えられたコードを変更する方法を求めている場合は、私のコードの残りの部分は、この

#include <iostream> 
using namespace std; 

// Returns the nth number in the fibonacci sequence 
int fib(int n); 

int main() 
{ 
    cout << fib(46) << endl; 

    system("pause"); 
    return 0; 
} 

int fib(int n) 
{ 
    // Base cases 
    if (n == 1 || n == 2) return 1; 

    // Recursive cases 
    return fib(n-1) + fib(n-2); 
} 

おかげでみんな

+2

ええと、あなたは私たちの許可を得ています。あなたの質問は何ですか? –

+1

"fib"への呼び出しをメモしたいとおっしゃいますか?つまり、パフォーマンスのために以前に計算された値を保存する方法を尋ねていますか? – Perry

+0

これは宿題のようなにおいがする。 – hochl

答えて

0

です値を入力する代わりに、ここには方法があります:

// Stores the numbers of the fibonacci sequence up to n inside buff 
void fib(int n,int* buff); 

int main() 
{ 
    //the array to store the fibonacci series 
    int buff[47]; 
    unsigned int i; 

    //call the recursive fibonacci which will populate the array 
    fib(46,buff); 

    //let's also print it 
    for(i = 0; i < 47; i ++) 
    { 
     printf("%d\n",buff[i]); 
    } 

    return 0; 
} 

// Stores the numbers of the fibonacci sequence up to n inside buff 
void fib(int n,int* buff) 
{ 

    // Base cases 
    if (n == 1) 
    { 
     buff[n-1] = 0; 
     buff[n] = 1; 
     return ; 
    } 

    //place the recursive call after the base cases 
    fib(n-1,buff); 

    //and here stores the result in the buffer 
    buff[n] = buff[n-1] + buff[n-2]; 
    return; 
} 
0

フィボナッチ数の定義は、F = 0を考慮に入れません。

シーケンスのインクリメンタルな拡張を可能にするために、コードを修正しました。それは必要な数だけを計算し、後のために高い数値を延期します。 F のデータ型を変更することなくリクエストすることはできません(long longは多少役に立ちます)。

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

static vector<int> fib_seq; 

// Returns the nth number in the fibonacci sequence        
int fib(int n); 

int main() 
{ 
    cout << fib(46) << endl; 

    system("pause"); 
    return 0; 
} 

int fib(int n) 
{ 
    // Make sure that there are at least two entries        
    if(fib_seq.size() < 2) { 
    fib_seq.resize(2); 
    fib_seq[0] = 0; 
    fib_seq[1] = 1; 
    } 
    // Fill the sequence with more numbers if needed        
    for(int i = (int)fib_seq.size(); i <= n; ++i) 
    fib_seq.push_back(fib_seq[i-2] + fib_seq[i-1]); 
    // Return the requested number             
    return fib_seq[n]; 
} 
関連する問題