How to memoize a recursive function in c++ with precision
I'm writing a program to find the Lucas Number using a recurrence relation. I used a map to store the values but when I run the program it'll output the correct values for the input up to an input of 45 roughly. For example 60 returns 18446744073418719042 when the solution for 60 is 3461452808002 After that the output is incorrect. I'm not sure where my precision starts to fail.
#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;
}
Here is the Main function class. Hopefully this will help clarify anything
#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 %llun" , n , lucasNumber( n ) );
}
catch( exception e ){
cerr << "ERROR" << endl;
}
}
c++
|
show 12 more comments
I'm writing a program to find the Lucas Number using a recurrence relation. I used a map to store the values but when I run the program it'll output the correct values for the input up to an input of 45 roughly. For example 60 returns 18446744073418719042 when the solution for 60 is 3461452808002 After that the output is incorrect. I'm not sure where my precision starts to fail.
#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;
}
Here is the Main function class. Hopefully this will help clarify anything
#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 %llun" , n , lucasNumber( n ) );
}
catch( exception e ){
cerr << "ERROR" << endl;
}
}
c++
1
Looks like you have a bug. It is missing main()....Please see stackoverflow.com/help/mcve
– Christopher Pisz
Nov 12 '18 at 21:51
1
there is a main function its just in a different class
– user10091649
Nov 12 '18 at 21:53
how is the output wrong? integers have no precision, they are exact. (there is no output in the code you show btw)
– user463035818
Nov 12 '18 at 21:54
1
there is nothing wrong in the code you show. Please read about Minimal, Complete, and Verifiable example and try to provide one. We dont know what output you are looking at or why you think it is wrong. Please include output and expected output in the question along with a mcve
– user463035818
Nov 12 '18 at 21:57
2
Using my power of omniscience, the bug is in the code not shown.
– Eljay
Nov 12 '18 at 22:00
|
show 12 more comments
I'm writing a program to find the Lucas Number using a recurrence relation. I used a map to store the values but when I run the program it'll output the correct values for the input up to an input of 45 roughly. For example 60 returns 18446744073418719042 when the solution for 60 is 3461452808002 After that the output is incorrect. I'm not sure where my precision starts to fail.
#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;
}
Here is the Main function class. Hopefully this will help clarify anything
#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 %llun" , n , lucasNumber( n ) );
}
catch( exception e ){
cerr << "ERROR" << endl;
}
}
c++
I'm writing a program to find the Lucas Number using a recurrence relation. I used a map to store the values but when I run the program it'll output the correct values for the input up to an input of 45 roughly. For example 60 returns 18446744073418719042 when the solution for 60 is 3461452808002 After that the output is incorrect. I'm not sure where my precision starts to fail.
#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;
}
Here is the Main function class. Hopefully this will help clarify anything
#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 %llun" , n , lucasNumber( n ) );
}
catch( exception e ){
cerr << "ERROR" << endl;
}
}
c++
c++
edited Nov 12 '18 at 22:06
asked Nov 12 '18 at 21:47
user10091649
1
Looks like you have a bug. It is missing main()....Please see stackoverflow.com/help/mcve
– Christopher Pisz
Nov 12 '18 at 21:51
1
there is a main function its just in a different class
– user10091649
Nov 12 '18 at 21:53
how is the output wrong? integers have no precision, they are exact. (there is no output in the code you show btw)
– user463035818
Nov 12 '18 at 21:54
1
there is nothing wrong in the code you show. Please read about Minimal, Complete, and Verifiable example and try to provide one. We dont know what output you are looking at or why you think it is wrong. Please include output and expected output in the question along with a mcve
– user463035818
Nov 12 '18 at 21:57
2
Using my power of omniscience, the bug is in the code not shown.
– Eljay
Nov 12 '18 at 22:00
|
show 12 more comments
1
Looks like you have a bug. It is missing main()....Please see stackoverflow.com/help/mcve
– Christopher Pisz
Nov 12 '18 at 21:51
1
there is a main function its just in a different class
– user10091649
Nov 12 '18 at 21:53
how is the output wrong? integers have no precision, they are exact. (there is no output in the code you show btw)
– user463035818
Nov 12 '18 at 21:54
1
there is nothing wrong in the code you show. Please read about Minimal, Complete, and Verifiable example and try to provide one. We dont know what output you are looking at or why you think it is wrong. Please include output and expected output in the question along with a mcve
– user463035818
Nov 12 '18 at 21:57
2
Using my power of omniscience, the bug is in the code not shown.
– Eljay
Nov 12 '18 at 22:00
1
1
Looks like you have a bug. It is missing main()....Please see stackoverflow.com/help/mcve
– Christopher Pisz
Nov 12 '18 at 21:51
Looks like you have a bug. It is missing main()....Please see stackoverflow.com/help/mcve
– Christopher Pisz
Nov 12 '18 at 21:51
1
1
there is a main function its just in a different class
– user10091649
Nov 12 '18 at 21:53
there is a main function its just in a different class
– user10091649
Nov 12 '18 at 21:53
how is the output wrong? integers have no precision, they are exact. (there is no output in the code you show btw)
– user463035818
Nov 12 '18 at 21:54
how is the output wrong? integers have no precision, they are exact. (there is no output in the code you show btw)
– user463035818
Nov 12 '18 at 21:54
1
1
there is nothing wrong in the code you show. Please read about Minimal, Complete, and Verifiable example and try to provide one. We dont know what output you are looking at or why you think it is wrong. Please include output and expected output in the question along with a mcve
– user463035818
Nov 12 '18 at 21:57
there is nothing wrong in the code you show. Please read about Minimal, Complete, and Verifiable example and try to provide one. We dont know what output you are looking at or why you think it is wrong. Please include output and expected output in the question along with a mcve
– user463035818
Nov 12 '18 at 21:57
2
2
Using my power of omniscience, the bug is in the code not shown.
– Eljay
Nov 12 '18 at 22:00
Using my power of omniscience, the bug is in the code not shown.
– Eljay
Nov 12 '18 at 22:00
|
show 12 more comments
1 Answer
1
active
oldest
votes
The following listing works fine for me. I only made very small edits so that I could debug it. Examine how I output the entire calculated sequence to file, so we can see where things went wrong, if they went wrong.
#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;
}
}
I made the storage global rather than static,but tried it both ways and it worked fine. In the real world, it would be a class member in a calculator class. Are you sure you are testing the listing you gave us? It appears fine to me, using VS2017 64 bit!
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
add a comment |
Your Answer
StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");
StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});
function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});
}
});
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53270590%2fhow-to-memoize-a-recursive-function-in-c-with-precision%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
1 Answer
1
active
oldest
votes
1 Answer
1
active
oldest
votes
active
oldest
votes
active
oldest
votes
The following listing works fine for me. I only made very small edits so that I could debug it. Examine how I output the entire calculated sequence to file, so we can see where things went wrong, if they went wrong.
#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;
}
}
I made the storage global rather than static,but tried it both ways and it worked fine. In the real world, it would be a class member in a calculator class. Are you sure you are testing the listing you gave us? It appears fine to me, using VS2017 64 bit!
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
add a comment |
The following listing works fine for me. I only made very small edits so that I could debug it. Examine how I output the entire calculated sequence to file, so we can see where things went wrong, if they went wrong.
#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;
}
}
I made the storage global rather than static,but tried it both ways and it worked fine. In the real world, it would be a class member in a calculator class. Are you sure you are testing the listing you gave us? It appears fine to me, using VS2017 64 bit!
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
add a comment |
The following listing works fine for me. I only made very small edits so that I could debug it. Examine how I output the entire calculated sequence to file, so we can see where things went wrong, if they went wrong.
#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;
}
}
I made the storage global rather than static,but tried it both ways and it worked fine. In the real world, it would be a class member in a calculator class. Are you sure you are testing the listing you gave us? It appears fine to me, using VS2017 64 bit!
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
The following listing works fine for me. I only made very small edits so that I could debug it. Examine how I output the entire calculated sequence to file, so we can see where things went wrong, if they went wrong.
#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;
}
}
I made the storage global rather than static,but tried it both ways and it worked fine. In the real world, it would be a class member in a calculator class. Are you sure you are testing the listing you gave us? It appears fine to me, using VS2017 64 bit!
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
edited Nov 13 '18 at 1:23
answered Nov 12 '18 at 23:21
Christopher PiszChristopher Pisz
1,457521
1,457521
add a comment |
add a comment |
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Some of your past answers have not been well-received, and you're in danger of being blocked from answering.
Please pay close attention to the following guidance:
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53270590%2fhow-to-memoize-a-recursive-function-in-c-with-precision%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
1
Looks like you have a bug. It is missing main()....Please see stackoverflow.com/help/mcve
– Christopher Pisz
Nov 12 '18 at 21:51
1
there is a main function its just in a different class
– user10091649
Nov 12 '18 at 21:53
how is the output wrong? integers have no precision, they are exact. (there is no output in the code you show btw)
– user463035818
Nov 12 '18 at 21:54
1
there is nothing wrong in the code you show. Please read about Minimal, Complete, and Verifiable example and try to provide one. We dont know what output you are looking at or why you think it is wrong. Please include output and expected output in the question along with a mcve
– user463035818
Nov 12 '18 at 21:57
2
Using my power of omniscience, the bug is in the code not shown.
– Eljay
Nov 12 '18 at 22:00