For HW #17 |
f(x) = { | x/2
if x is even 3x+1 otherwise |
As we saw in class, this program has a "bug"; for some reason, it never stops. Find its bug. (Note: it may have several bugs. Work on the program until everything works as it should.)
////////////////////////////////////////////////////
var x // x serves as input
x = 3
var c // c counts the number of iterations
c = 0
if(x==1) document.write("<br> we reached 1 in 0 iterations")
while(x != 1)
{
var d // another counter
var y
y = x
while(y >= d) // this loop is to tell if x is even or odd
{
if(x==d) {x=x/2 ; c++}
d++
if(x==d) {x=3*x+1; c++}
d++
}
}
document.write("<br> We reached 1 in c steps")
///////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////
function collatz(x)
{
if(x==1) return(0)
if(x%2==0) return(1+collatz(x/2))
return(1+collatz(3*x+1))
}
var z=3
document.write("<br> Input: ",z, " ; Number of iterations: ", collatz(3))
///////////////////////////////////////////////////////////////