0

3x+1 conjecture

on my computer, I have the following script in the head: <script> var x = prompt("Choose a number"); var a = x%2; /* For testing if it is an even number */ var b = 0; while(x!=1) { switch (a) { case 0: x = (3*x)+1; break; case 1: x = x/2; } var a=x%2; ++b; } </script> And in the body I got this one: <script> document.write("It takes "b + "steps" + " for this number in the 3x+1-conjecture to reach one."); </script> And this didnt work. What did I do wrong?

9th Aug 2016, 4:57 PM
Jefta Pruim
Jefta Pruim - avatar
2 Réponses
0
oh sorry that was a typomistake in te comment. on my pc i have a semicolomb
10th Aug 2016, 11:02 AM
Jefta Pruim
Jefta Pruim - avatar
0
maybe you need to round off the number a? if the user picks x = 10. then 3 * 10 + 1 is 31. then a = 31 % 2 = 1. then it loops. because a is 1, x = 31 / 2 = 15.5. then a = 15.5 % 2 = 1.5. then it loops. now the loop is stuck because a is neither 0 or 1, but 1.5. you can round off a with either Math.floor(a), Math.ceil(a) or Math.round(a). im guessing you need to use Math.floor(a). Math.floor(1.5) = 1. please note I have not tested this code.
6th Nov 2016, 4:27 AM
Birk
Birk - avatar