簡體   English   中英

項目歐拉解決方案#14

[英]Project Euler Solution #14

我有以下問題(來自ProjectEuler.net - 問題14

為正整數集定義以下迭代序列:

n -> n/2 (n is even)
n -> 3n + 1 (n is odd)

使用上面的規則並從13開始,我們生成以下序列:

13 → 40 → 20 → 10 → 5 → 16 → 8 → 4 → 2 → 1

可以看出,該序列(從13開始並在1 )包含10個項。 雖然尚未證實(Collat​​z問題),但據認為所有起始數字都是1

哪個起始編號低於一百萬,產生最長的鏈?

注意:鏈條啟動后,條款允許超過一百萬。

我用了:

   static int road (int n)
   {
       int road = 0;
       while (n != 1)
       {
           if (n % 2 == 0)
               n = n / 2;
           else
               n = 3 * n + 1;
           road++;
       }
       return road;
   }
   static void Main(string[] args)
   {
       int max = 0, num = 0;
       for (int i = 1; i < 1000000; i++)
       {
           if (road(i) > max)
           {
               max = road(i);
               num = i;
           }
       }
       Console.WriteLine(num);
   }

但是沒有打印輸出。

(我不打算給你一個完整的解決方案,因為歐拉項目旨在讓思考,而不是我們已經解決了問題的人。)

嘗試確定鏈中的值有多大 ,並記住整數類型限制

function problem14(){

    function r(p,n){
        return cl(p)>cl(n)?p:n;
    }

    function c(n){
        return n%2===0?n/2:3*n+1;
    }

    function cl(n){
        var _a = 1;
        var _n = n;
        while(_n !== 1){
            _a++;
            _n = c(_n);
        }
        return _a;
    }

    var b = [];
    var m = 20;
    var i = 500000;
    while(i < 1000000){
        var _n = cl(i);
        if(_n>m){
            b.push(i);
            m = _n;
        }
        i++;
    }

    return b.reduce(r);

}

這是我的js代碼。

它不是“沒有輸出”,它只是運行很長時間。 如果將for循環的上限更改為100000,您將很快看到輸出。 它運行很長的原因是你使用未經檢查的整數,並且你不應該在你想要的地方獲得溢出。 幾秒后打破,你會看到負面的n

嘗試以下方法,即使用checked關鍵字,它將說明我的意思:

// will now throw OverflowException with large n
checked
{
    int road = 0;
    while (n != 1)
    {
        if (n%2 == 0)
            n = n/2;
        else
            n = 3*n + 1;
        road++;
    }
    return road;
}

首先,請注意您每次迭代都會調用road()函數兩次,這會浪費處理時間(對於“帶有副作用的函數”,可能會產生不必要的后果)。

其次,由於整數溢出,你無法得到答案 - 例如,值113383最終在相同的20左右數字周圍循環

-122,-61,-182,-91,-272,-136,-68,-34,-17,-50,-25,-74,-37,-110,-55,-164, - 82,-41,-122

哎呀!

暫無
暫無

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

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