我正在编写一个程序以使用递归关系查找卢卡斯编号。我使用了一个映射来存储值,但是当我运行该程序时,它将为输入输出正确的值,直到大约45个输入为止。例如,当60的解决方案是3461452808002时,60返回18446744073418719042,之后输出不正确。我不确定我的精度在哪里开始下降。
#include <map>
#include <iterator>
using namespace std;
unsigned long long int lucasNumber( unsigned long long int n ){
static std::map<unsigned long long int,unsigned long long int> values;
if(n == 0) {
return 2;
} else if(n == 1) {
return 1;
}
std::map<unsigned long long int,unsigned long long int>::iterator iter = values.find(n);
if(iter == values.end()) {
return values[n] = lucasNumber(n-1) + lucasNumber(n-2);
} else {
return iter->second;
}
这是Main函数类。希望这将有助于澄清一切
#include <stdio.h>
#include "csce310homeWork04part01.hpp"
#include <cstdio>
#include <cstdlib>
#include <iostream>
using namespace std;
int main( int argc , char* argv[] ){
unsigned long long int n;
cin >> n;
try{
fprintf( stdout , "Lucas number %llu has a value of %llu\n" , n , lucasNumber( n ) );
}
catch( exception e ){
cerr << "ERROR" << endl;
}
}
答案 0 :(得分:0)
以下列表对我来说效果很好。我只做了很小的编辑,以便可以调试它。检查我如何将整个计算出的序列输出到文件,以便我们可以查看哪里出错了,如果出错了。
#include <iostream>
#include <fstream>
#include <map>
using namespace std;
typedef std::map<unsigned long long, unsigned long long> StorageType;
StorageType g_previouslyCalculatedValues{ {0, 2}, {1, 1} };
// Calculate Lucas Numbers up to the index specified
unsigned long long LucasNumber(unsigned long long n)
{
StorageType::iterator iter = g_previouslyCalculatedValues.find(n);
if (iter == g_previouslyCalculatedValues.end()) {
return g_previouslyCalculatedValues[n] = LucasNumber(n - 1) + LucasNumber(n - 2);
}
return iter->second;
}
int main(int argc, char* argv[])
{
unsigned long long int n;
cout << "Enter the index of Lucas numbers to calculate" << endl;
if ((cin >> n).fail())
{
cout << "Use an unsigned integer next time. Exiting..." << endl;
return -1;
}
try
{
StorageType::value_type result = LucasNumber(n);
// Debug
ofstream myfile("results.txt");
for (auto element : g_previouslyCalculatedValues)
{
myfile << element.first << "\t: " << element.second << endl;
}
myfile.close();
}
catch (exception e)
{
cerr << "ERROR" << endl;
}
}
我使存储成为全局存储,而不是静态存储,但同时尝试了两种方法,并且运行良好。在现实世界中,它将是计算器类的类成员。您确定要测试您提供给我们的列表吗?使用VS2017 64位对我来说似乎很好!
Expected result: 3461452808002
Actual result: 3461452808002
From command line:
Enter the index of Lucas numbers to calculate
60
The lucas number for 60 is 3461452808002