我正在创建一个程序,它将两个变量作为用户提示。第一个是起始数字,下一个是确定范围的数字。然后,该程序使用 collatz 函数吐出输入的原始数字达到零需要多少步,然后将此信息显示到屏幕上。然后它应该将起始编号增加 1 并重复该过程,直到起始编号达到第二个输入的数字
目前我只为一个号码工作,这是原始的起始号码。我不确定如何编写 collatz 函数以遍历起始编号(第一个输入)和范围编号(第二个输入)之间的所有数字我的猜测是我需要某种 for 循环并推送一个值数组(数字达到 0 所需的步骤)作为另一个数组中的自己的数组(其中包含程序运行的所有数字的所有步骤)
如果有人可以提供帮助,我将不胜感激,谢谢
var numArray = [];
function getStartNum(){
startNum = parseInt(prompt('Please enter a starting number greater than 0.'));
if(!isPosNum(startNum)){
alert("error! That is an incorrect value. Please renter an appropriate positive value.");
getStartNum();
} else {
numArray.push(startNum);
getRangeNum();
}
}
function getRangeNum(){
rangeNum = parseInt(prompt('Please enter a range value greater than 0.'));
if(!isPosNum(rangeNum)){
alert("error! That is an incorrect value. Please renter an appropriate positive value.");
getRangeNum();
} else {
collatz();
}
}
function isPosNum( number ) {
if (isNaN( number )) {
return false;
} else if (number < 0) {
return false;
} else if (number == 0) {
return false;
} else {
return true;
}
}
function collatz() {
//sets x to always be the value of the last element in the array
x = numArray[numArray.length-1];
//Sets y to the remainder of x
y = x % 2;
//if the value of y of 0, then the number is even and these calculations will be performed
if (x == 1) {
console.log('X has reached a value of 1');
createBar();
} else if ( y == 0) {
console.log('Number is even.');
z = x/2;
console.log('Value of z is equal to ' + z);
numArray.push(z);
console.log(numArray);
collatz();
} else if ( y !== 0) {
//If y is not equal to 0 then it is odd, and these calculations will be performed
console.log('Number is odd.');
z = (3 * x) + 1;
console.log('Value of z is equal to ' + z);
numArray.push(z);
console.log(numArray);
collatz();
}
}
function maxValueIndex() {
}
function createBar() {
var steps = numArray.length-1;
console.log('Number of steps taken to get to 1 is: ' + steps);
var p = document.createElement("p");
document.body.appendChild(p);
var first = numArray[0];
var output = document.getElementsByTagName("p")[0];
output.innerHTML = 'Number of steps taken for ' + first + ' to reach 1 is: ' + steps;
var g = document.createElement("div");
g.id = "graph";
document.body.appendChild(g);
for ( var i=0, n=numArray.length-1; i < n; i++) {
var line = document.createElement("p");
line.className = "line";
line.innerHTML = "|";
document.body.appendChild(line);
}
}
getStartNum();