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


Pip, 23 21 bytes

Wa>1&Uia:%a?3*a+1a/2i


Replit! Or, here's the original 23-byte version in Pip Classic: Try it online!

Explanation

Wa>1&Uia:%a?3*a+1a/2i
i is 0; a is first command-line argument (implicit)
Wa>1                   While a>1
&Ui                (and if it is, increment i):
a:               Set a to:
%a?             If a mod 2 is nonzero (a is odd),
3*a+1         3*a+1;
a/2      else, a/2
i  Autoprint i, the iteration count


Racket, 51 characters, 28 brackets

(define(a n)(do([i 0(+ i 1)][x n(if(even? x)(/ x 2)(+ 1(* 3 x)))])((= 1 x) i)))


Praise the do. Love the do.

• Welcome to Code Golf! Nice first answer. Dec 13 '21 at 23:33
INPUT A
Y:
IF A MOD 2=0 THEN
B=A/2
PRINT B
A=B
ELSE
B=A*3+1
PRINT B
A=B
END IF
IF A>1 THEN
GOTO Y
ELSE
END IF

New contributor
serdar evren is a new contributor to this site. Take care in asking for clarification, commenting, and answering. Check out our Code of Conduct.
• Welcome to Code Golf! Could you edit in the language used, along with the length (in bytes) of your code, as this is a [code-golf] challenge? I've edited your answer slightly to format the code properly yesterday

Axiom, 74 bytes

g(a)==(c:=0;repeat(a<=1=>break;c:=c+1;a rem 2=0=>(a:=a quo 2);a:=3*a+1);c)


ungolfed

gg(a)==
c:=0
repeat
a<=1     =>break
c:=c+1
a rem 2=0=>(a:=a quo 2)
a:=3*a+1
c


results

(3) -> [i,g(i)] for i in [2,16,5,7,1232456,123245677777777777777777777777777]
Compiling function g with type PositiveInteger -> NonNegativeInteger
(3)
[[2,1], [16,4], [5,5], [7,16], [1232456,191],
[123245677777777777777777777777777,572]]
Type: Tuple List NonNegativeInteger


R, 57 55 bytes

x=scan();n=0;while(x-1){x='if'(x%%2,3*x+1,x/2);n=n+1};n


Not much to say, uses a nice statement within the while loop, which should become 0 -> False only when x=1, similar to the check whether x is odd or even. This also uses the implicit conversion of 0->False and nonzero -> True.

Saved 2 bytes thanks to a trick by @Billywob used in this answer.

• Abusing a built-in (F) saves 4 bytes - the other change is just a different way of doing the if, not golfier. Jun 14 '18 at 19:35

c 1=0
c x|odd x=1+c(3*x+1)|1<2=1+c(xdiv2)


Usage: c 7-> 16

• What's "Haskell 2"? Dec 6 '16 at 23:14
• @nyuszika7h: a typo
– nimi
Dec 6 '16 at 23:14

C#, 71 bytes

Assuming output is required as opposed to just a return

n=>{int i=0;while(n>1){n=n%2<1?n/2:n*3+1;i++;}System.Console.Write(i);}


Java (OpenJDK), 53 bytes

n->{int i=0;for(;n>1;i++)n=n%2<1?n/2:n*3+1;return i;}


Try it online!

Java 8, 53 bytes

i->{for(;i>1;)System.out.print(i=i&1>0?i=3*i+1:i/2);}


Another solution(Java 9)

i->IntStream.iterate(i,j->j&1>0?j*3+1:j/2).takeWhile(n->true);


TI-Basic, 47 bytes

Prompt A
0→B
While A-1
Aremainder(A+1,2_/2+(3A+1)remainder(A,2→A
B+1→B
End
B


S.I.L.O.S, 76 bytes

readIO
lbla
I=1-(i%2)
if I x
i=i*6+2
lblx
i/2
x+1
I=1-i
I|
if I a
printInt x


Try it online!

Somewhat naively implements the spec. It avoids a couple extra lines at the cost of performance by multiplying i by 6 and adding 2, then dividing by two when the number is odd.

Emojicode, 139 bytes

🐖🔢➡️🚂🍇🍮a🐕🍮i 0🔁❎😛1a🍇🍊😛1🚮a 2🍇🍮a➕1✖3a🍉🍓🍇🍮a➗a 2🍉🍮i➕1i🍉🍎i🍉


Try it online!

Clean, 82 bytes

import StdEnv
?n=snd(until(\(e,_)=e<2)(\(e,i)=(if(isOdd e)(3*e+1)(e/2),i+1))(n,0))


Try it online!

Stax, 12 bytesCP437

ÄFl,rBoU¡£&╦


14 bytes when unpacked,

1{h_3*^\_@gt%v


Run and debug online!

SNOBOL4 (CSNOBOL4), 96 bytes

	N =INPUT
T	X =X + 1
N =GT(REMDR(N,2)) 3 * N + 1	:S(O)
N =N / 2
O	OUTPUT =EQ(N,1) X	:F(T)
END


Try it online!

D,f,@,dd2/i@3*1+$2%D +? -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!

Il&+1t~j+1*3\~/2<~<
>:1)k~tO@~:k\:  nl


Try it online!

Ruby, 77 72 bytes

b=0;a=gets.to_i;loop{if a==1;p b;exit;end;a.odd?? (a*=3;a+=1):a/=2;b+=1}


Definitely not the shortest, but not the most unreadable or hard to follow either. Try it online!

a.odd?? (a*=3;a+=1): uses the ternary operator, which is a short form of if/then/else. It looks like boolean ? instruction : instruction, with the first instruction being if the boolean is true, and the second being if it isn't. Therefore trailing question mark and colon.

*= and /= are the multiplication and division versions of += in Ruby.

Ungolfed version:

counter = 0
input = gets.to_i
loop do
if input = 1
print counter
exit
end
if input.odd?
input *= 3
input += 1
else
input /= 2
end
counter += 1
end


SmileBASIC, 54 bytes

INPUT N
WHILE N-1D=1AND N
C=C+1N=N*3*D+D+N/2*!D
WEND?C


c n|n==1=0|even n=1+c(div n 2)|odd n=1+c(3*n-1)


Ungolfed:

c n
| n == 1 = 0
| even n = 1 + c (div n 2)
| odd n  = 1 + c (3*n-1)


A recursive function that returns the number of times it's been run, excluding when n==1.

Python 3, 64 bytes

def f(n,a=0):
while n>0:n=[n//2,n*3+1][n%2];a+=1
yield a


Try it online!

HBL, 16 15 bytes

?(%.)(+(*.<))(/.2
?(-.)(-+?().


Try it!

Explanation

Helper function:

?(%.)(+(*.<))(/.2
?                  If
.               the argument
(% )              is odd:
(+     )       Increment
(*  )        the product of
.          the argument
<         and 3
Else:
(/     Divide
.    the argument
2   by 2


Main function:

?(-.)(-+?().
?             If
(- )         decrementing
.          the argument
is truthy (nonzero):
(-        Chain these functions together:
+        Increment
?       Call current function recursively
()     Call previous function
.   and apply to the argument


The use of the chain macro may be easier to understand in Thimble, HBL's ungolfed companion language:

(-+?().)
=>
(chain inc recur prev arg1)
=>
(inc (recur (prev arg1)))