簡體   English   中英

遞歸堆棧溢出 C++

[英]Recursion Stack Overflow C++

我是 C++ 的新手,但認為處理一些項目 Euler 問題會使我熟悉該語言。

嘗試Project Euler 問題 14:最長 Collat​​z 序列時

我無法讓我的 C++ 解決方案工作,但我的 python 解決方案沒有問題......

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")

並得到

starting key 837799 has length 525
1.399820327758789 seconds

我的 C++ 嘗試......(我認為是等價的......)

#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;
}

在調試模式下在 Visual Studio 中運行此程序時,出現以下錯誤

Unhandled exception at 0x00007FF75A64EB70 in
0014_longest)collatz_sequence_cpp.exe: 0xC00000FD: Stack overflow
(parameters: 0x0000000000000001, 0x000000DC81493FE0).

有人告訴我應該使用指針在堆上進行分配,但使用指針的經驗非常有限......

我不明白的另一件事是......當我在主體循環中使用 100'000 而不是 1'000'000 運行它時,它可以工作但非常慢。

提示:Collat​​z 序列提供的n范圍的不變量(數學上)是什么,您的 Python 代碼滿足但您的 C++ 代碼不滿足? 提示提示:在實際發生堆棧溢出之前n的最后幾個值是多少?

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM