c++ - Modified Fibbonaci C++ getting a large negative number
问题描述
Ok so, I'm doing hackerrank's Fibonacci modified question. I am able to solve this question only when the iteration goes to 8 anything pass that and it starts returning a large negative number. I thought this was because of an integer overflow so I changed my types to unsigned long long yet the problems still persist. Any help is appreciated.
Link to original problem: https://www.hackerrank.com/challenges/fibonacci-modified/problem
#include <iostream>
#include <vector>
using namespace std;
int modFib(unsigned t1, unsigned t2, unsigned n) {
if (n == 1) {
return t1;
}
else if (n == 2) {
return t2;
} else {
return modFib(t1, t2, n-2) + (modFib(t1, t2, n-1) * modFib(t1, t2, n-1));
}
}
int main() {
cout << modFib(0, 1, 10) << endl;
return 0;
}
//Expected output is 84266613096281243382112
//I get -1022889632
解决方案
In C++, the general range of an unsigned int
is 0 to 4,294,967,295
, so using an unsigned int
will not be appropriate for this problem.
The expected output is actually larger than the maximum possible value of even an unsigned long long int
, which goes from 0 to 18,446,744,073,709,551,615
. This means that you cannot use either of these data types for this problem.
For such large values, you should look into the usage of BigNums
.
推荐阅读
- c++ - 对于黑客等级中的“两个字符串”问题,我在三个测试用例中遇到分段错误。是什么原因?
- c++ - 为什么我的 while 函数没有终止?
- javascript - 来自 .env 项的链接在 Vue.js 中被销毁
- angular - Cytoscape.js 并在订阅中加载数据
- c# - 更新 c# 项目安装程序
- python - TypeError:“ReadFile”Op 的输入“文件名”的类型为 float32,与预期的字符串类型不匹配
- javascript - Babel 没有在 Expo 中转换 TypeScript
- typescript - webgl 项目中的打字稿配置。意外的标记:在 typescript lint 错误中标记类型时
- python-3.x - 如何从 Telethon 装饰器方法返回列表或变量
- gps - 如何使用 GPS 创建本地 ADA 库?