创建一个数组以将计算出的数字存储在内存中

时间:2012-02-25 04:35:39

标签: c++ arrays

我试图创建一个数组来存储公式中的计算数字并将它们放入内存中。因此,稍后再次调用该数字时,不必重新计算。导致它已经在记忆中。

公式是

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 个答案:

答案 0 :(得分: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;
}

答案 1 :(得分:0)

您对Fibonacci数字的定义不考虑 F 0 = 0。

这是对代码的修改,以允许序列的增量扩展。它只计算它需要的数字,并推迟更高的数字。请注意,如果不切换数据类型,您将无法请求高于 F 46 的数字(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];
}