如何在javascript中制作Ulam号码序列?

时间:2015-08-20 13:17:54

标签: javascript html

我无法解决这个问题,我已经检查了我的代码,但我不知道问题是什么。

这就是问题:数学家Ulam建议从任何正整数n(n> 0)生成一系列数字,如下所示。

    if n is 1, it will stop.
    if n is even, the next number is n/2.
    if n is odd, the next number is 3 * n + 1.
    continue with the process until reaching 1.
    here some examples for the first few integers.
    2->1
    3->10->5->16->8->4->2->1
    4->2->1
    6->3->10->5->16->8->4->2->1
    7->22->11->34->17->52->26->13->40->20->10->5->16->8->4->2->1
    Sample Run:
    Enter Positive Integer: 5
    The ulam Number Sequence is : 5->16->8->4->2->1

这是我的代码......

<!DOCTYPE html>
<html>
<head>
<title>Ulam Number Sequence</title>
</head>
<body>
<form name="myform" onsubmit=" return false">
Enter positive integer: <input type="number" id="num" required>
<button onclick="process()">Process</button>
<button onclick="Reset()">Reset</button>
</form>
<p id = "info"> </p>
<script>


function isOdd(num) {
    var odd = true;
    for (var i = 0; i <= num; i++) {
       if (num % i == 0) {
           odd = false;
           break;
       }
    }
    return odd;
  }
  function isEven(num) {
    var even = true;
    for (var i = 0; i <= num; i++) {
       if (num % i == 1) {
           even = false;
           break;
       }
    }
    return even;
  }
function process(){
var n = parseInt(document.getElementById("num").value);
var result1 = [];


for(var i = 0; i <= n; i++){

    if(isOdd(i)){
        result1[result1.length] = i /2;

    }
    if(isEven(i)){

        result1[result1.length] = 3 * i + 1;
    }

    if(isOdd(result1)){
        result1[result1.length] = result1 / 2;
    }
    if(isEven(result1)){

        result1[result1.length] = 3 * result1 +1;
    }

    //result1[result1.length] = i * 3 + 1;
   document.getElementById("info").innerHTML = result1.join("->");
    }
   }




   function Reset(){
   document.getElementById("info").innerHTML = "";
   document.getElementById("num").value = "" ; 
  }

   </script>
   </body>
   </html>

1 个答案:

答案 0 :(得分:0)

也许这对你来说是一个解决方案(还有一点提示):

function process() {
    var n = parseInt(document.getElementById('num').value),
        result = [n];

    if (isFinite(n) && n && n === Math.abs(n)) {
        while (n !== 1) {
            // basically this is all to do.
            n = n % 2 ? 3 * n + 1 : n / 2;
            result.push(n);
        }
        document.getElementById("info").innerHTML = result.join(' > ');
    } else {
        document.getElementById("info").innerHTML = 'Does not compute!';
    }
}

function reset() {
    document.getElementById('info').innerHTML = '';
    document.getElementById('num').value = ''
}
<form name="myform" onsubmit=" return false">
    Enter positive integer: <input type="number" id="num" required>
    <button onclick="process()">Process</button>
    <button onclick="reset()">Reset</button>
</form>
<p id="info"></p>