Collatz Conjecture
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.
(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.
Challenge
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.
Comments
zkvarz
Jan 17, 3:12 AMQuite simple, one problem was to stop the toop, eventually I've managed it.
David
Mar 16, 1:27 PMFor 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.
Mikas
May 24, 10:39 AMWhats wrong with my code? It keeps giving me the "Runtime error"
Melany
May 27, 4:23 AM@Mikas Your else says "num = num * 3 - 1" it should be +1.
Jig
Jun 21, 5:42 AMI dont understand why would 3-1 cause runtime error?
Learneroo
Jun 21, 10:26 PM@Jig, you can get stuck in a loop, eg 5, 14, 7, 20, 10, 5 ...
Jig
Jun 25, 1:40 AMHow did you know that it would get stuck in a loop. Thanks for the insight. Love what you guys are doing.
Bernard Mitchell
Jul 2, 2:23 PM@Learneroo should I create two loops?
Learneroo
Jul 2, 2:59 PM@Bernard, that's not necessary. You can create one
while
loop, with a condition inside it that determines what number to go to next.Ravi
Jul 30, 7:21 AMyour correct output's are wrong.
for input=5 , the output should be 16 8 4 2 1
Learneroo
Jul 30, 10:00 AMSorry, due to a change yesterday it was mistakenly showing the number 5 for the count, it's been fixed.