# Collatz Conjecture (OEIS A006577)

This is the Collatz Conjecture (OEIS A006577):

• Repeat the following steps:
• If n is even, divide it by 2.
• If n is odd, multiply it by 3 and add 1.

It is proven that for all positive integers up to 5 * 260, or about 5764000000000000000, n will eventually become 1.

Your task is to find out how many iterations it takes (of halving or tripling-plus-one) to reach 1.

Rules:

• Shortest code wins.
• If a number < 2 is input, or a non-integer, or a non-number, output does not matter.

Test cases

2  -> 1
16 -> 4
5  -> 5
7  -> 16


# PARI/GP, 38 bytes

a(n)=if(n==1,0,a(if(n%2,3*n+1,n/2))+1)


Try it online!

Equivalent to this readable C code:

int b(n)
{
if (n % 2)
return 3 * n + 1;
else
return n / 2;
}

int a(n)
{
if (n == 1)
return 0;
else
return a(b(n)) + 1;
}


# Casio-Basic, 83 72 bytes

71 bytes for code, +1 for n as parameter.

0⇒z
While n≠1
piecewise(mod(n,2),3n+1,n/2)⇒n
z+1⇒z
WhileEnd
Print z


# tinylisp repl, 68 bytes

(load library)(d f(q((n)(i(e n 1)0(inc(f(i(even? n)(/ n 2)(inc(* 3 n


Try it online! (Note that the repl auto-closes parentheses; on TIO, they have to be explicitly closed, which I've done in the footer.)

This is the same recursive solution as, e.g., Carcigenicate's Clojure answer. Because tinylisp has only addition and subtraction built in, I load the standard library to get even?, /, and * (and inc, which is the same length as a 1 but looks nicer). Other library functions would make the code longer; for instance, I'm defining the function manually with (q((n)(...))) rather than using (lambda(n)(...)). Here's how it would look ungolfed and indented:

(load library)
(def collatz
(lambda (n)
(if (equal? n 1)
0
(inc
(collatz
(if (even? n)
(/ n 2)
(inc (* 3 n))))))))


Going the other direction, here's a 101-byte solution that doesn't use the library. The E function returns n/2 if n is even and the empty list (falsey) if n is odd, so it can be used both to test evenness and to divide by 2.*

(d E(q((n _)(i(l n 2)(i n()_)(E(s n 2)(a _ 1
(d f(q((n)(i(e n 1)0(a 1(f(i(E n 0)(E n 0)(a(a(a n n)n)1


* Only works for strictly positive integers, but that's exactly what we're dealing with in this challenge.

## QBIC, 34 33 bytes

:{~-a|_Xb\b=b+1~a%2|a=a*3+1\a=a/2


Pretty straightforward:

:           Name the Command Line Parameter 'a'
{           Start an infinite loop
~-a|_Xb     If 'a' = 1 (or -a = -1, QB's TRUE value), quit printing 'b'
\           ELSE (a > 1)
b=b+1       Increment step counter
~a%2        In QBasic, 8 mod 2 yields 0, and 0 is considered false
|a=a*3+1    Collatz Odd branch
\a=a/2      Collatz Even branch


# Attache, 11 bytes

CollatzSize


Try it online!

Not much to say...

# Acc!!, 127 75 bytes

Count u while N/49 {
_+1
}
Count i while _-1 {
_/2+_%2*(5*_/2+2)
Write 49
}


The program takes input and produces output in unary. Try it online!

(Here's a decimal I/O version in 209 bytes.)

# Read input in unary
Count u while N/49 {   # Increment u from 0 while input character is >= "1"
_+1                  # Add one to accumulator
}

# Main loop
Count i while _-1 {    # Increment i from 0 while accumulator is not equal to 1
_/2+_%2*(5*_/2+2)    # Apply one step of Collatz function to accumulator
Write 49             # Write "1" to output
}


The expression _/2+_%2*(5*_/2+2) boils down to

_/2,               if _%2 is 0
_/2 + (5*_)/2 + 2, if _%2 is 1


This is integer division, so the latter case comes out to

_/2 + 2*_ + _/2 + 2
= 2*_ + (_/2)*2 + 2
= 2*_ + _ + 1
= 3*_ + 1


## Wumpus, 22 bytes

I]=2:~3*)=&~~!0~.
l(O@


Try it online!

### Explanation

The first line is the main loop which iterates the Collatz function until we get 1. We keep track of the number of steps by growing the stack by one element on each iteration.

I   Read a decimal integer N from STDIN. At EOF (i.e. on subsequent
]   Rotate the stack right. On the first iteration, this does nothing, but
afterwards this moves the 0 to the bottom of the stack.
=   Duplicate N.
2:  Compute N/2.
~   Swap with the other copy of N.
3*) Compute 3N+1.
=   Duplicate.
&~  3N+1 times: swap N/2 and 3N+1. If N is odd, 3N+1 is even and vice versa.
We end up with the value that we want on top and the incorrect one
underneath.
~   Swap them once more.
!   Logical NOT. 3N+1 is always positive and N/2 gives 0 iff N = 1 (in which
case N/2 will also be on top of the stack). So this essentially gives us
1 iff N = 1 (and 0 otherwise). Call this value y.
0~. Jump to (0, y), i.e. to the beginning of the second line once we reach N = 1
and to the beginning of the first line otherwise.


Once we reach 1:

l   Push the stack depth. The stack holds one zero for each iteration as well
as the final result. But note that we won't terminate until the iteration
that process 1 itself (because we check the condition at the end of
the loop, but based on its initial N). So the stack depth is one
greater than the number of steps to reach 1.
(   Decrement.
O   Print as decimal integer.
@   Terminate the program.


I've got an alternative 22 byte solution, but unfortunately I haven't found anything shorter yet:

I]3*)=2%5*):=(!0~.
lO@


# Java (OpenJDK 8), 54 bytes

a->{int c=0;for(;a!=1;c++)a=a%2>0?a*3+1:a/2;return c;}


Try it online!

This answer is a little to simple to justify an explanation, it’s just a while loop and a ternary expression.

# Octave, 65 bytes

@(x)eval 'k=0;do++k;if mod(x,2)x=3*x+1;else x/=2;end,until x<2,k'


Try it online!

It's time we have an Octave answer here. It's a straight forward implementation of the algorithm, but there are several small golfs.

Using do ... until instead of while ... end saves some bytes. Instead of having while x>1,k++;...end, we could have do++k;...until x<2, saving two bytes. Using eval in an anonymous function saves a few bytes, compared to having input(''). Also, skipping the parentheses in the eval call saves some bytes.

# Ruby, 48 bytes

(f=->n{n>1&&1+f[n%2<1?n/2:3*n+1]||0})[gets.to_i]


Same as other Ruby, but using n%2?a:b syntax instead of [a,b][n%2]. Saves one char.

• You mention that you save one byte off of the other Ruby answer yet your answer is 13 bytes longer because of (...)[gets.to_i]. Even if I remove that (which doesn't break your answer) you still have the same length as the other answer. This is ok, I just thought maybe you might have made a mistake. – Ad Hoc Garf Hunter Jun 19 '18 at 14:11

## PHP, 80 73 Bytes

Tried a recursive function Try it here! (80 Bytes)

Try it online (73 Bytes)

Code (recursive function)

function f($n,$c=0){echo($n!=1)?(($n%2)?f($n*3+1,$c+1):f($n/2,$c+1)):$c;}  Output 16 -> 4 2 -> 1 5 -> 5 7 -> 16  Explanation function f($n,$c=0){ //$c counts the iterations, $n the input echo($n!=1)?
(($n%2)? f($n*3+1,$c+1): //$n is odd
+?
-1
W,+1,$f>x,},+1,},-1 } O  Try it online! -5 bytes thanks to rubber duck golfing! ## How it works D,f,@, ; Define a function 'f' that takes one argument ; Example argument: [10] dd ; Triplicate; STACK = [10 10 10] 2/i ; Halve; STACK = [10 10 5] @ ; Reverse; STACK = [5 10 10] 3*1+ ; (n*3)+1; STACK = [5 10 31]$	; Swap;		STACK = [5 31 10]
2%	; Parity;	STACK = [5 31 0]
D	; Select;	STACK = [5]

+?		; Take input; 	x = 10;	y = 0;
-1		; Decrement;	x = 9;	y = 0;

W,		; While x != 0:
+1,	;  Increment;	x = 10;	y = 0;
\$f>x,	;  Call 'f';	x = 5;	y = 0;
},+1,	;  Increment y;	x = 5;	y = 1;
},-1	;  Decrement x;	x = 4;	y = 1;

}		; Swap to y;	x = 0;	y = 6;
O		; Output y;


# dc, 30 28 bytes

?[d5*2+d2%*+2/d1<f1+]dsfx1-p


## Explanation

?                             # read input
[            d1<f  ]dsfx     # repeat until we reach 1
d5*2+d2%*+2/                # n → (n + (5n+2)%2 * (5n+2)) / 2
1+          # count iterations
1-p  # decrement and print result


?[6*4+]sm[d2~1=md1!=f]dsfxz1-p


We keep all the intermediate results on the stack, then count the size of the stack. We save bytes by always doing the division by two, but if the remainder is 1, then we multiply by 6 and add 4 (3 for the remainders and 1 for the Collatz constant). The final stack count contains all the numbers we've seen; the number of operations is one less than that.

# Explanation

?                               # input

[6*4+]sm                        # helper function

[d2~1=md1!=f]dsfx               # recursion

z1-p                            # print result


# Julia 0.6, 43 bytes

c(n,l=0)=n<2?l:n%2>0?c(3n+1,l+1):c(n/2,l+1)


Try it online!