Collatz Conjecture

Collapse Content

The Collatz Conjecture (which was seen in the If Challenge), goes like this:

Take any number n. If n is even, divide it by 2, if n is odd, multiply it by 3 and add 1. Repeat the process indefinitely, and you'll eventually reach 1.

A Collatz sequence is the sequence of number generated from a specific number.

Collatz Conjecture XKCD

(From XKCD.)

Input/Output Format
Boilerplate code is provided for Java. For other languages, read in the numbers from the standard input in the following format:

  • The input starts with N, the number of cases.
  • N lines follow, which each contains 1 integer.

Print out the correct numbers for each case on its own line.

Click on "View Raw I/O" below to view sample input and output.


Given a num variable, can you print all the numbers in num's Collatz sequence until 1 is reached? Print the numbers space-separated (and each test case on its own line).

Please sign in or sign up to submit answers.

Alternatively, you can try out Learneroo before signing up.


  • 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){
  • @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.

  • @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.

  • 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.

All Node Comments
Contact Us
Sign in or email us at [email protected]