制作一个数组,将计算出的数字存储在内存中

Make an array to store the calculated numbers in memory

本文关键字:计算 数字 存储 内存 数组 一个      更新时间:2023-10-16

我试图制作一个数组来存储公式中计算出的数字,并将它们放入内存。这样,以后当再次调用该数字时,就不必重新计算。因为它已经在记忆中了。

公式为

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

谢谢各位

您对斐波那契数的定义没有考虑F0=0。

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

如果您正在询问如何修改给定的代码,以便它可以保存值,而不仅仅是将它们打印到控制台,那么这里有一种方法:

// 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("%dn",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;
}