Collatz Conjecture (OEIS A006577)

GolfScript, 24 23 21 20 18 chars

~{(}{3*).2%6\?/}/,

Assumes input on stdin. Online test


C - 50 47 characters

Poor little C unfortunately requires an awful amount of code for basic I/O, so shorting all that down has made the UI slightly unintuitive.

b;main(a){return~-a?b++,main(a&1?3*a+1:a/2):b;}

Compile it with for example gcc -o 1 collatz.c. The input is in unary with space-separated digits, and you will find the answer in the exit code. An example with the number 17:

$> ./1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
$> echo $?
12
$>

Perl 34 (+1) chars

$\++,$_*=$_&1?3+1/$_:.5while$_>1}{

Abusing $\ for final output, as per usual. Run with the -p command line option, input is taken from stdin.

Saved one byte due to Elias Van Ootegem. Specifically, the observeration that the following two are equivalent:

$_=$_*3+1
$_*=3+1/$_

Although one byte longer, it saves two bytes by shortening $_/2 to just .5.

Sample usage:

$ echo 176 | perl -p collatz.pl
18

PHP 54 bytes

<?for(;1<$n=&$argv[1];$c++)$n=$n&1?$n*3+1:$n/2;echo$c;

Javascript's archnemesis for the Wooden Spoon Award seems to have fallen a bit short in this challenge. There's not a whole lot of room for creativity with this problem, though. Input is taken as a command line argument.

Sample usage:

$ php collatz.php 176
18

Tags:

Math

Code Golf