制作一个数组,将计算出的数字存储在内存中
Make an array to store the calculated numbers in memory
我试图制作一个数组来存储公式中计算出的数字,并将它们放入内存。这样,以后当再次调用该数字时,就不必重新计算。因为它已经在记忆中了。
公式为
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;
}
相关文章:
- 从文本文件中的每一行读取数字,并计算数字重复的次数
- 使用正则表达式C++计算数字中的十进制空格
- 此代码如何计算数字的奇偶校验?
- 如何计算数字 x 的频率
- 计算数字范围内特定数字的出现次数
- 递归函数,用于计算数字中的位数
- 我正在尝试编写一个函数来计算C++数字的数字根,但在编译后出现错误
- 努力理解一个以十六进制、十进制、bin 和 dec 计算数字总和的程序
- 在C 中计算数字的问题
- 在一系列数字的间隔内计算数字
- 计算数字的幂
- 用递归计算数字的位数
- C++,计算正数和负数并计算数字的平均值)编写一个读取未指定数量的整数的程序
- 如何在 c++ 中计算数字的第 3 个根
- 计算数字中偶数位数
- 计算数字平方根的程序
- 计算数字x的位数,其数字和等于x*m的数字和
- 是否有可能在编译时计算数字的阶乘,但不使用枚举?
- 计算可被 K 整除的范围内的数字,并在范围内计算数字之和
- 不使用字符串计算数字中的数字