87
\$\begingroup\$

This is the Collatz Conjecture (OEIS A006577):

  • Start with an integer n> 1.
  • 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.

Relevant xkcd :)

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
Seggan
7,12228 silver badges53 bronze badges
asked Aug 1, 2013 at 11:22
\$\endgroup\$
0

149 Answers 149

1
\$\begingroup\$

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.

answered May 12, 2018 at 20:29
\$\endgroup\$
1
\$\begingroup\$

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.

answered Jun 14, 2018 at 17:35
\$\endgroup\$
1
  • \$\begingroup\$ 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. \$\endgroup\$ Commented Jun 19, 2018 at 14:11
1
\$\begingroup\$

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
 f($n/2,$c+1)) //$n is even
:$c; //echo $c (counter) when n ==1
}
answered Mar 26, 2018 at 13:23
\$\endgroup\$
1
  • \$\begingroup\$ No, the test cases aren't part of the byte count. Your submission looks fine as it is. \$\endgroup\$ Commented Mar 26, 2018 at 13:42
1
\$\begingroup\$

Python 2, 48 bytes

f=lambda n,s=0:s*(n<2)or f((n/2,3*n+1)[n%2],s+1)

Try it online!

Aaah, recursion.

# s*0 or s*1.
s*(n<2)
# while n>1, this will evaluate to 0 or f(n,s+1).
# Since positive integers are Truthy, this will return f().
# when n<2, this will return s without evaluating f().
s*(n<2)or f(...)
answered Sep 13, 2018 at 16:28
\$\endgroup\$
1
\$\begingroup\$

JavaScript, 35 bytes

f=(n,c)=>n<2?c:f(n%2?n*3+1:n/2,-~c)

Try it online!

answered Jan 23, 2019 at 22:05
\$\endgroup\$
1
\$\begingroup\$

Japt, (削除) 18 (削除ここまで) 15 bytes

É©Òß[U*3ÄUz]gUv

Try it

answered Feb 21, 2018 at 15:14
\$\endgroup\$
1
\$\begingroup\$

Wren, 68 bytes

Fn.new{|n|
var c=0
while(n>1){
n=n%2==0?n/2:n*3+1
c=c+1
}
return c
}

Try it online!

Explanation

Fn.new{|n| // New anonymous function with param n
var c=0 // Declare a variable c as 0
while(n>1){ // While n is larger than 1:
n=n%2==0? // If n is divisible by 2:
 n/2: // Halve n
 n*3+1 // Otherwise, triple n & increment.
c=c+1 // Increment the counter
} // This is here due to Wrens bad brace-handling system
return c // Return the value of the counter
}
answered Dec 12, 2019 at 12:59
\$\endgroup\$
1
\$\begingroup\$

Keg -rR, 23 bytes (SBCS)

I really need to remember those new instructions.

0&{:1>|:2%[3*9|1⁄2](6)

Try it online!

answered Dec 12, 2019 at 12:41
\$\endgroup\$
1
1
\$\begingroup\$

Kotlin, 63 bytes

{var n=it
var c=0
while(n>1){n=if(n%2==0)n/2 else n*3+1
c++}
c}

Try it online!

answered Mar 22, 2020 at 5:56
\$\endgroup\$
1
\$\begingroup\$

MAWP, 36 bytes

@[!!2P2WA{%3W1M}<%2P>1A{1M}/1M\]%1A:

Works as per the basic rules. Increments existing 1 in stack for each step.

Prints out n-1.

Try it!

answered Aug 26, 2020 at 9:26
\$\endgroup\$
1
\$\begingroup\$

Rust, 62 bytes

fn c(x:u8)->u8{if x==1{0}else{c(if x%2==0{x/2}else{x*3+1})+1}}

This recursively determines the total. For 2 extra bytes u8 can be changed to u64 to support all 64-bit integers instead of just 8-bit ones.

answered Feb 28, 2021 at 0:08
\$\endgroup\$
1
  • 1
    \$\begingroup\$ Welcome to the site, and nice first answer! Be sure to check out our Tips for golfing in Rust page for ways you can golf your program \$\endgroup\$ Commented Feb 28, 2021 at 0:33
1
\$\begingroup\$

Lua, 75 bytes

function C(x)z=0 while x>1 do x=({x//2,3*x+1})[x%2+1]z=z+1 end return z end

Try it online!

caird coinheringaahing
50.9k11 gold badges133 silver badges364 bronze badges
answered Mar 1, 2021 at 14:28
\$\endgroup\$
1
\$\begingroup\$

Python - 101 bytes

n=int(input())
m=0
while n>1:
 if n%2==0:
 n=n/2
 m+=1
 else:
 n=3*n+1
 m+=1
if n==1:
 print(m)

This assumes n is inputted to STDIN as an integer. If it is not explicitly that, a type check is most certainly possible, but would cost a few bytes, i.e.

if type(n) != int: 
 print(N/A)

(edit 1: input is so expensive)

answered Mar 15, 2021 at 20:56
\$\endgroup\$
1
  • 1
    \$\begingroup\$ 71 bytes \$\endgroup\$ Commented Apr 10, 2022 at 3:55
1
\$\begingroup\$

Burlesque, 26 bytes

1{J2dv{2./}{3.*+.}IE}C~1Fi

Try it online!

1 #Needed for C~
{
 J #Duplicate
 2dv #Even
 {2./} #Halve
 {3.*+.} #3n+1
 IE #If even, else
}
C~ #Continue indefinitely
1Fi #Find index of 1
answered Nov 22, 2021 at 17:56
\$\endgroup\$
1
\$\begingroup\$

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!

answered Dec 7, 2021 at 18:24
\$\endgroup\$
1
\$\begingroup\$
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
caird coinheringaahing
50.9k11 gold badges133 silver badges364 bronze badges
answered Jan 23, 2022 at 20:29
\$\endgroup\$
1
  • 7
    \$\begingroup\$ 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 \$\endgroup\$ Commented Jan 23, 2022 at 20:31
1
\$\begingroup\$

tinylisp, (削除) 68 (削除ここまで) 67 bytes

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

Try it online!

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 odd?, /, *, and inc. 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 (odd? n)
 (add2 (* 3 n) 1)
 (/ n 2)))))))

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.

answered Oct 26, 2017 at 21:43
\$\endgroup\$
1
\$\begingroup\$

Desmos, 63 bytes

i->.5si(5k+1)+sk-s+1,o->o+s
i=\ans_0
o=0
k=mod(i,2)
s=sign(i-1)

Output is the value of o after the code finishes running.

Have fun trying to figure out how this works! (It's really not as complicated as it seems)

Try It On Desmos!

Try It On Desmos! - Prettified

answered Apr 10, 2022 at 3:08
\$\endgroup\$
1
\$\begingroup\$

Ruby, 60 bytes

n,i=gets.to_i,0;while n>1 do n=n%2==0?n/2:n*3+1;i+=1 end;p i

Pretty readable and easy to understand compared to the previous Ruby submission.

Attempt This Online!

answered Apr 10, 2022 at 3:51
\$\endgroup\$
1
  • \$\begingroup\$ 56 bytes \$\endgroup\$ Commented Apr 10, 2022 at 20:17
1
\$\begingroup\$

Factor + project-euler.014, 22 bytes

[ collatz length 1 - ]

Try it online!

answered May 8, 2022 at 20:19
\$\endgroup\$
1
\$\begingroup\$

Haskell (54 bytes)

c n a|n<2=a|odd n=c(3*n+1)(a+1)|even n=c(div n 2)(a+1)

This function takes two arguments, the value n and an accumulator a. The type signature is: c :: Int -> Int -> Int.

In expanded form:

collatz n acc
 | n < 2 = acc
 | odd n = collatz (3 * n + 1) (acc + 1)
 | even n = collatz (div n 2) (acc + 1)
answered May 10, 2022 at 13:04
\$\endgroup\$
1
1
\$\begingroup\$

brev, 71 bytes

(rec(f x)(cond((= x 1)0)((odd? x)(+(f(+(* 3 x)1))1))(1(+(f(/ x 2))1))))
answered Aug 21, 2022 at 19:50
\$\endgroup\$
1
\$\begingroup\$

Fig, \15ドル\log_{256}(96)\approx\$ 12.347 bytes

#?{x}oX?Ox}*3xH

Try it online!

This challenge does not lend itself well to Fig's implicit inputs...

#?{x}oX?Ox}*3xH
 {x # Decrement the input
#? # If ^ is false, return ^, else return...
 oX # Call this function with the following argument:
 ?Ox # If odd
 *3x # Multiply by 3
 } # Add 1
 # Else
 H # Halve
 } # After calling this function, increment the result
answered Oct 3, 2022 at 20:28
\$\endgroup\$
1
\$\begingroup\$

Vyxal, (削除) 17 (削除ここまで) (削除) 12 (削除ここまで) 11 bytes

∷[T›|1⁄2)İ2ḟ⇧

Try it Online!

-5 bytes thanks to lyxal

Removed flag thanks to emanresu A.

answered Apr 10, 2022 at 1:10
\$\endgroup\$
4
  • \$\begingroup\$ Try it Online! for 12 bytes \$\endgroup\$ Commented Apr 10, 2022 at 3:04
  • \$\begingroup\$ Flagless 11 (husk port) \$\endgroup\$ Commented Jan 30, 2023 at 7:00
  • \$\begingroup\$ @emanresuA Alternative: ‡(½‡T›iİ2ḟ⇧ \$\endgroup\$ Commented Jan 30, 2023 at 18:20
  • \$\begingroup\$ Try it Online! for 10 bytes/7.875 bytes. Uses newer functionality that didn't exist back when this answer was made. \$\endgroup\$ Commented Jul 18, 2023 at 13:28
1
\$\begingroup\$

Thunno 2, 17 bytes

(×ばつ+:1⁄2;ẋ)x−

Attempt This Online!

Only works in Thunno \$\le 2.1.9\$. In versions \$\ge 2.1.10\$, can be replaced with ẋ+.

Explanation

(×ばつ+:1⁄2;ẋ)x− # implicit input; x is initialised to 1
(1Q; ) # while TOS != 1:
 D # duplicate
 ɗ? # if TOS is odd:
 ×ばつ+ # triple and increment
 : # else:
 1⁄2 # halve
 ;ẋ # increment x
 x− # push x and decrement
 # implicit output
answered Jun 3, 2023 at 18:15
\$\endgroup\$
1
\$\begingroup\$

><> (Fish), 31 bytes

:1=?\::2%?2,円
;nl~/i+1*3/
|.!0/

Try it

answered Jun 4, 2023 at 1:33
\$\endgroup\$
1
\$\begingroup\$

Nekomata, 10 bytes

l{1>e1⁄23*→I

Attempt This Online!

l{1>e1⁄23*→I
l{ Repeat the following function until it fails, and count the number of steps:
 1> Check if greater than 1
 e Parallelly apply the following two functions:
 1⁄2 Check if it is even, and divide by 2
 3*→ Multiply by 3 and add 1
 I Choose the first result that does not fail
answered Jun 4, 2023 at 2:38
\$\endgroup\$
1
\$\begingroup\$

Punchtape, 405 bytes & Punchcode, 50 bytes

I did this just for fun and showcase

Punchtape is an esoteric language trying to imitate punched tape, a form of data storage widely used by computers in the 1950s and 1960s.

Punchcode is the compiled (UTF-8) form of it.

There is no compiler or interpreter publicly accessible at the moment because I am still working on it.

punchtape

START|
O-OO-|
OOOO-|
----O|
---O-|
----O|
-----|
----O|
---O-|
----O|
---OO|
----O|
----O|
----O|
O--OO|
----O|
-----|
----O|
-----|
OOOO-|
---OO|
-----|
-OO--|
---O-|
O---O|
OOO-O|
--OO-|
--O-O|
OO-OO|
O--O-|
O--OO|
OOO-O|
--OOO|
--O--|
O-O--|
---O-|
-O--O|
OO-OO|
OOOO-|
---OO|
-----|
O----|
--OO-|
O--OO|
---O-|
--OOO|
-OO-O|
O-O--|
---O-|
-O--O|
-O-OO|

punchcode

(This contains characters that a lot of web browsers and fonts dont display or display them in a way that is inconvenient for showing code. To combat this, all characters have been shifted 32 times byte-wise to show as basic latin characters.)

6>!"! !"!#!!!3! ! ># ,"1=&%;23='4ドル");># 0&3"'-4")+

Here is the original form of the code, if you are curious:

 
 
answered Mar 11, 2024 at 19:24
\$\endgroup\$
1
\$\begingroup\$

Uiua, 23 bytes

⧻⍢(×ばつ3⟩◿2.|¬∊2)¤

Explain:

⧻ # length of list
 ⍢( | ) # do while
 ⊂0 # prepend 0 to the list
 ×ばつ3⟩◿2. # apply collatz the the whole list
 ¬∊2 # while the list doesn't contain 2
 ¤ # arg as list
answered Mar 15, 2024 at 22:14
\$\endgroup\$
1
\$\begingroup\$

TI-84 BASIC, 53 bytes

Input I
DelVar LWhile I≠1
L+1→L
remainder(I,2
(1+3I)Ans+.5Inot(Ans→I
End
Disp L
answered May 9, 2024 at 15:03
\$\endgroup\$

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.