visual c++ - Recursion C++
i new c++ thought working on project euler problems familiarize me language.
when attempting project euler problem 14: longest collatz sequence
i not manage c++ solution work, had no problem 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 in memo.keys(): return memo[a] if % 2 == 0: memo[a] = rec(a // 2) + 1 else: memo[a] = rec(3 * + 1) + 1 if memo[a] > longest_chain: longest_chain = memo[a] longest_starting_key = return memo[a] 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 thought 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 = 3; < 1000000; i++){ f(i); } std::cout << longest_chain << std::endl; }
when running in visual studio in debug mode following error
unhandled exception @ 0x00007ff75a64eb70 in 0014_longest)collatz_sequence_cpp.exe: 0xc00000fd: stack overflow (parameters: 0x0000000000000001, 0x000000dc81493fe0).
someone told me should allocate on heap using pointers, have limited experience working pointers...
the other thing don't understand is... when run 100'000 instead of 1'000'000 in main body loop, works slow.
hint: invariant on range of n
collatz sequence provides (mathematically), python code satisfies c++ code doesn't? hint hint: last few values of n
before stack overflow occurs?
Comments
Post a Comment