[英]Integer overflow in unsigned long long array
我试图制作缓存的斐波那契序列,但似乎在第 n 个 position = 247 之后遇到 integer 溢出(即使数据类型是 unsigned long long),编译器输出奇怪的错误否定结果,这是我不希望的。 想知道除了 n = 247 之外的解决方案是什么,以及如何将准确结果提高到基本上 n = 任何正 integer 如果可能的话......谢谢。
我还试图将数组容量设置为 nthPos,但它只接受常量整数(甚至不接受常量变量)。 想知道有什么办法解决这个问题......
#include <iostream>
#include <cstdlib>
#include <string>
#include <time.h>
#include <cmath>
using namespace std;
int FibonacciRecursiveFunc(int nthPos) {
unsigned long long firstNum = 0; unsigned long long secondNum = 1;
unsigned long long PastFibonacciCache[300] = { firstNum,secondNum };
if (find(PastFibonacciCache, end(PastFibonacciCache), nthPos-1) != end(PastFibonacciCache)) {
return nthPos - 1;
}
else {
for (int i = 2; i < nthPos; i++) {
PastFibonacciCache[i] = PastFibonacciCache[i - 1] + PastFibonacciCache[i - 2];
if (i > 300) {
unsigned long long SecondLastTerm = PastFibonacciCache[299];
unsigned long long lastTerm = PastFibonacciCache[300];
PastFibonacciCache[300] = {}; PastFibonacciCache[0] = SecondLastTerm; PastFibonacciCache[1] = lastTerm;
i - 300; nthPos - 300;
}
}
return PastFibonacciCache[nthPos%300-1];
}
}
int main() {
string inputVAL; int nthPos;
cout << "Greetings, enter a valid n value | n >= 1\n" << "type exit, quit or break to quit program \n\n" << endl << " ->";
getline(cin, inputVAL);
string exit_Methods[3] = { "exit", "quit", "break" };
while (find(exit_Methods, end(exit_Methods), inputVAL) == end(exit_Methods)) {
bool exception_caught = true;
try {
nthPos = stoi(inputVAL);
exception_caught = false;
}
catch (invalid_argument) {
cerr << "invalid argument" << endl;
}
catch (out_of_range) {
cerr << "number is too big" << endl;
}
catch (exception) {
cerr << "something went horribly wrong :v" << endl;
}
if (!exception_caught) {
//begintimer for calculation speed
time_t begin, end;
time(&begin);
if (nthPos >= 1) {
cout << FibonacciRecursiveFunc(nthPos) << endl;
}
else {
cout << "ERR" << endl;
}
// measure elapsed time
time(&end);
time_t elapsed = end - begin;
printf("Time measured: %ld seconds.\n\n", elapsed);
}
cout << "enter a valid n value | n >= 0 ->";
getline(cin, inputVAL);
}
}
int FibonacciRecursiveFunc(int nthPos) {
您的 function 的返回类型是int
。 int
可表示的最大值因系统而异,但我们假设它在您的系统上为 2147483647。
第 247 个斐波那契数是 1152058411884454788302593034206568772452674037325128。这个数字大于 2147483647。你不能用int
表示这么大的数字。
想知道解决这个问题的方法是什么
您不能使用基本类型。 您可以使用任意精度算术。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.