Java Reference
In-Depth Information
function collatz(n,sequence) {
var sequence = sequence || [n]; // the sequence should
be an array
or start with first value
if (n%2 === 0) {// n is even
m = n/2;
} else { // n is odd
m = 3*n + 1;
}
sequence.push(m); // add the current value to the
sequence
if (m === 1) { // sequence has reached the end
return "Sequence took " + sequence.length + " steps";
} else { // carry on by invoking the sequence again
return collatz(m,sequence);
}
}
collatz(18);
<< "Sequence took 21 steps. It was
18,9,28,14,7,22,11,34,17,52,26,13
,40,20,10,5,16,8,4,2,1"
Have a go at using the function and see if you can find a value above 5 × 2 ⁶⁰ that doesn't
end in the loop—you'll be famous if you do!
 
Search WWH ::




Custom Search