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.
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
149 Answers 149
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'
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.
-
\$\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\$2018年06月19日 14:11:14 +00:00Commented Jun 19, 2018 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
f($n/2,$c+1)) //$n is even
:$c; //echo $c (counter) when n ==1
}
-
\$\begingroup\$ No, the test cases aren't part of the byte count. Your submission looks fine as it is. \$\endgroup\$Martin Ender– Martin Ender2018年03月26日 13:42:55 +00:00Commented Mar 26, 2018 at 13:42
Python 2, 48 bytes
f=lambda n,s=0:s*(n<2)or f((n/2,3*n+1)[n%2],s+1)
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(...)
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
}
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
}
-
\$\begingroup\$ -5 bytes with
-rRand new register commands \$\endgroup\$2019年12月13日 20:24:15 +00:00Commented Dec 13, 2019 at 20:24
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.
-
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\$2021年02月28日 00:33:16 +00:00Commented Feb 28, 2021 at 0:33
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
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)
-
1
Burlesque, 26 bytes
1{J2dv{2./}{3.*+.}IE}C~1Fi
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
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
-
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\$2022年01月23日 20:31:29 +00:00Commented Jan 23, 2022 at 20:31
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
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.
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)
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.
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)
-
1\$\begingroup\$ I forget where this is spelled out on Meta, but you can't expect extra input. Fortunately, it can be golfed more than enough to compensate (and without abandoning the accumulator, which would result in nimi's existing solution). \$\endgroup\$Unrelated String– Unrelated String2022年08月21日 03:04:46 +00:00Commented Aug 21, 2022 at 3:04
brev, 71 bytes
(rec(f x)(cond((= x 1)0)((odd? x)(+(f(+(* 3 x)1))1))(1(+(f(/ x 2))1))))
Fig, \15ドル\log_{256}(96)\approx\$ 12.347 bytes
#?{x}oX?Ox}*3xH
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
Vyxal, (削除) 17 (削除ここまで) (削除) 12 (削除ここまで) 11 bytes
∷[T›|1⁄2)İ2ḟ⇧
-5 bytes thanks to lyxal
Removed flag thanks to emanresu A.
-
\$\begingroup\$ Try it Online! for 12 bytes \$\endgroup\$2022年04月10日 03:04:27 +00:00Commented Apr 10, 2022 at 3:04
-
\$\begingroup\$ Flagless 11 (husk port) \$\endgroup\$emanresu A– emanresu A2023年01月30日 07:00:06 +00:00Commented Jan 30, 2023 at 7:00
-
\$\begingroup\$ @emanresuA Alternative:
‡(½‡T›iİ2ḟ⇧\$\endgroup\$naffetS– naffetS2023年01月30日 18:20:09 +00:00Commented 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\$2023年07月18日 13:28:24 +00:00Commented Jul 18, 2023 at 13:28
Thunno 2, 17 bytes
(×ばつ+:1⁄2;ẋ)x−
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
Nekomata, 10 bytes
l{1>e1⁄23*→I
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
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:
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
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