LoginSignup
0
1

More than 3 years have passed since last update.

JavaScriptでコラッツ予想の動作を実行

Posted at

コラッツ予想の動作を確認してみる

JavaScriptでコラッツ予想の動作を実行するプログラムを作成してみました。

・自然数を入力する
・「偶数なら2で割り、奇数なら3倍して1を足す」という操作を繰り返す
・1になったら終了する

上記操作で必ず1になってプログラムが停止する、というのが「コラッツ予想」です。
「予想」と呼ばれるとおり、2020年現在証明はされていません。

コラッツ予想.png

CollatzProblem.html
<html>
<head>
  <meta http-equiv="Content-Type" context="text/html; charset=UTF-8" />
  <meta charset="UTF-8" />
  <title>JavaScriptでコラッツ予想</title>
<script>

function doCalc() {
    var txtN1 = document.getElementById("txtN1");

    var n1, n2, strResult;
    var vWork = [];
    var vOut = [];

    n1 = parseInt(txtN1.value, 10);
    n2 = n1;

    vOut.push("" + n1);

    while (1) {
        if (n2 <= 1) { break; }

        if (n2 % 2 == 0) {
            n1 = n2
            n2 = n2 / 2;
            strResult = "" + n1 + " / 2 = " + n2;
            vOut.push(strResult);
        } else {
            n1 = n2
            n2 = n2 * 3 + 1;
            strResult = "" + n1 + " * 3 + 1 = " + n2;
            vOut.push(strResult);
        }
    }

    document.getElementById("result").innerHTML = vOut.join("\n");
}

</script>
</head>
<body>

<h2>コラッツ予想</h2>

<ul>
<li>自然数を入力する</li>
<li>「偶数なら2で割り、奇数なら3倍して1を足す」という操作を繰り返す</li>
<li>1になったら終了する</li>
</ul>

4桁 まで
<input type="text" id="txtN1" value="" maxlength="4" size="7" oninput="value = value.replace(/[^0-9]+/i,'');" />
<input type="button" value="計算" onclick="doCalc()" /><br />
<br />

<textarea id="result" rows="50" col="20" style="width:700px;height:400px;">
</textarea>

</body>
</html>
0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1