Collatz Conjecture Comments

Comments

  • Quite simple, one problem was to stop the toop, eventually I've managed it.

  • For me it wasn't about stopping the loop but actually how to get the number print the first time(initial input) and the last time (1) without having the loop interfering.

  • Whats wrong with my code? It keeps giving me the "Runtime error"

    public static void doStuff(int num){
        System.out.print(num + " ");
        while(num > 1){
    
    cont...
  • @Mikas Your else says "num = num * 3 - 1" it should be +1.

  • I dont understand why would 3-1 cause runtime error?

  • @Jig, you can get stuck in a loop, eg 5, 14, 7, 20, 10, 5 ...

  • How did you know that it would get stuck in a loop. Thanks for the insight. Love what you guys are doing.

  •     while(num != 1){
            System.out.print(num+" ");
        if(num%2==0) {
            num = num/2;
            } else {
            num = num*3+1;
            }
        }   System.out.print("1");
    
  • @Learneroo should I create two loops?

  • @Bernard, that's not necessary. You can create one while loop, with a condition inside it that determines what number to go to next.

  • @learneroo that what I figured ...a for loop wouldn't work here.

  • @learneroo that was a question...thanks

  • Inside the loop, you can check if num divides by two or not, and then set num to the appropriate value.

    (See a solution if you're still stuck.)

  • I got it right , but I'm not sure I understand how the if statements work in conjunction with the loops. Thanks

  • the while loop will repeatedly run through the code (in its body) while a specified condition is true. anything can happen inside the loop body. in this case, an if-else

    cont...
  • your correct output's are wrong.
    for input=5 , the output should be 16 8 4 2 1

  • Sorry, due to a change yesterday it was mistakenly showing the number 5 for the count, it's been fixed.

Contact Us
Sign in or email us at [email protected]