I am new to C++ but thought that working on some project Euler problems would familiarize me with the language.
When attempting Project Euler Problem 14: Longest Collatz sequence
I could not manage to get my C++ solution to work, but had no problem with my python solution...
import time
start = time.time()
memo = {1:1,2:2}
longest_chain, longest_starting_key = 2, 2
def rec(a):
global longest_chain, longest_starting_key
if a in memo.keys():
return memo[a]
if a % 2 == 0:
memo[a] = rec(a // 2) + 1
else:
memo[a] = rec(3 * a + 1) + 1
if memo[a] > longest_chain:
longest_chain = memo[a]
longest_starting_key = a
return memo[a]
for i in range(1000000,3,-1): rec(i)
print("starting key", longest_starting_key , ": has length", longest_chain)
print((time.time() - start), "seconds")
and got
starting key 837799 has length 525
1.399820327758789 seconds
My C++ attempt... (that I thought was equivalent...)
#include <iostream>
#include <unordered_map>
std::unordered_map<int, int> mem = { {1,1},{2,2} };
int longest_chain{ 2 }, best_starting_num{ 2 };
bool is_in(const int& i){
auto search = mem.find(i);
if(search == mem.end())
return false;
else
return true;
}
int f(int n){
if(is_in(n))
return mem[n];
if(n % 2)
mem[n] = f(3 * n + 1) + 1;
else
mem[n] = f(n / 2) + 1;
if(mem[n] > longest_chain)
longest_chain = mem[n];
return mem[n];
}
int main(){
for(int i = 3; i < 1000000; i++){
f(i);
}
std::cout << longest_chain << std::endl;
}
When running this in Visual Studio in debug mode I get the following error
Unhandled exception at 0x00007FF75A64EB70 in
0014_longest)collatz_sequence_cpp.exe: 0xC00000FD: Stack overflow
(parameters: 0x0000000000000001, 0x000000DC81493FE0).
Someone told me that I should allocate on the heap using pointers, but have very limited experience with working with pointers...
The other thing I don't understand is... when I run it with 100'000 instead of 1'000'000 in the main body loop, it works but is very slow.
Hint : What is the invariant on the range of n
that the Collatz sequence provides (mathematically), which your Python code satisfies but your C++ code doesn't? Hint to the hint: what are the last few values of n
before your stack overflow actually occurs?
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.