| Bytes | Lang | Time | Link |
|---|---|---|---|
| 269 | Bespoke | 250827T075215Z | Josiah W |
| 055 | C# 10 | 250321T152545Z | juanferr |
| 014 | Vyxal 3 | 250226T091817Z | Weird Gl |
| 050 | Raku Perl 6 rakudo | 250321T160219Z | xrs |
| 083 | SAKO | 250321T123323Z | Acrimori |
| 880 | ArnoldC | 250304T111503Z | Themooni |
| 040 | Swift 6 | 250302T020937Z | macOSist |
| 038 | AWK | 250227T172106Z | xrs |
| 021 | Jalapeño | 250212T042321Z | ATaco |
| 073 | Periodically | 250207T193033Z | madeforl |
| 068 | ibe | 241121T201528Z | madeforl |
| 053 | TI84 BASIC | 240509T150353Z | madeforl |
| 070 | Acc!! | 171128T092436Z | DLosc |
| 023 | Uiua | 240315T221403Z | Zylviij |
| 405 | Punchtape | 240311T192451Z | madeforl |
| 010 | Nekomata | 230604T023859Z | alephalp |
| 031 | ><> Fish | 230604T013313Z | chunes |
| 017 | Thunno 2 | 230603T181516Z | The Thon |
| 011 | Vyxal | 220410T011007Z | naffetS |
| 052 | Python 2 | 130801T181403Z | Valentin |
| 040 | Gambit scheme | 130801T172344Z | Valentin |
| nan | Fig | 221003T202818Z | Seggan |
| 071 | brev | 220821T195046Z | Sandra |
| 011 | Husk | 220821T022522Z | DLosc |
| 023 | Pyth 23byte | 220821T015313Z | bigbean |
| 019 | Pip | 200830T222312Z | DLosc |
| 037 | Knight | 220820T215259Z | 97.100.9 |
| 012 | Jelly | 160418T065245Z | Dennis |
| 026 | Alice | 170414T220109Z | Martin E |
| 054 | Haskell | 220510T130442Z | Ed The & |
| 022 | Factor + projecteuler.014 | 220508T201903Z | chunes |
| 021 | ngn/k | 220324T005057Z | ulucs |
| 037 | C gcc | 220408T063122Z | Qaziquza |
| 060 | Ruby | 220410T035105Z | oeuf |
| 063 | Desmos | 220410T030840Z | Aiden Ch |
| 217 | LOLCODE | 220410T011924Z | naffetS |
| 085 | rusty_deque | 220409T222813Z | bigyihsu |
| 067 | Rust | 220324T040232Z | Sapherey |
| 038 | Haskell | 220323T160040Z | matteo_c |
| 029 | Julia 1.0 | 220217T214148Z | MarcMush |
| 027 | Julia 0.6 | 160418T175023Z | Dennis |
| 054 | Julia | 220215T021942Z | David Sc |
| 015 | x86 machine code | 220215T014757Z | EasyasPi |
| 067 | tinylisp | 171026T214357Z | DLosc |
| nan | 220123T202946Z | serdar e | |
| 028 | Racket | 211213T225910Z | gantz gi |
| 015 | HBL | 211207T185249Z | DLosc |
| 064 | Python 3 | 211207T182459Z | Alan Bag |
| 026 | Burlesque | 211122T175651Z | DeathInc |
| 028 | ><> | 160414T095649Z | Aaron |
| 090 | BitCycle u | 201011T035450Z | DLosc |
| 101 | Python | 210315T205607Z | user1008 |
| 075 | Lua | 210301T142856Z | J. А. de |
| 062 | Rust | 210228T000809Z | smitop |
| 071 | Forth gforth | 201110T095837Z | Razetime |
| 047 | Haskell | 200831T034151Z | bigyihsu |
| 036 | MAWP | 200826T092651Z | Razetime |
| 845 | FRACTRAN | 200420T044447Z | Anders K |
| 063 | Kotlin | 200322T055618Z | snail_ |
| 024 | FRACTRAN | 200321T205737Z | AviFS |
| 023 | Keg rR | 191212T124105Z | user8505 |
| 068 | Wren | 191212T125923Z | user8505 |
| 054 | SmileBASIC | 170201T235000Z | 12Me21 |
| 033 | Aceto | 170512T103223Z | L3viatha |
| 015 | 05AB1E | 190117T192310Z | Wisław |
| 072 | Ruby | 190128T044534Z | CG One H |
| 015 | Japt | 180221T151409Z | Shaggy |
| 035 | JavaScript | 190123T220537Z | Oliver |
| 023 | ><> | 160505T113612Z | Sok |
| 024 | Pushy | 181224T214336Z | FlipTack |
| 4333 | C gcc | 170404T232446Z | Bijan |
| 007 | MathGolf | 180913T140101Z | maxb |
| 010 | Jelly | 181112T235315Z | Bubbler |
| 048 | Python 2 | 180913T162842Z | Triggern |
| 038 | Ahead | 180716T100339Z | snail_ |
| 043 | Julia 0.6 | 180616T154933Z | Sundar R |
| 073 | PHP | 180326T132317Z | Francisc |
| 048 | Ruby | 180614T173503Z | Joey |
| 016 | MATL | 180512T211213Z | Stewie G |
| 065 | Octave | 180512T202906Z | Stewie G |
| 157 | Emojicode | 180509T165222Z | X1M4L |
| 054 | Java OpenJDK 8 | 180326T124321Z | X1M4L |
| 028 | dc | 180509T142903Z | Toby Spe |
| 044 | Hexagony | 180327T105510Z | Jo King |
| 035 | Ruby | 180509T055929Z | G B |
| 050 | Add++ | 180411T214503Z | caird co |
| 029 | Befunge93 | 180408T094021Z | Jo King |
| 056 | brainfuck | 171227T142611Z | Jo King |
| 016 | Brachylog | 180302T131701Z | Martin E |
| 096 | SNOBOL4 CSNOBOL4 | 180221T160943Z | Giuseppe |
| nan | Stax | 180221T154437Z | Weijun Z |
| 022 | Wumpus | 180221T141104Z | Martin E |
| 082 | Clean | 180109T200729Z | Οurous |
| 037 | Python 2 | 160601T032342Z | Dennis |
| 061 | Emacs/Common Lisp | 180109T034525Z | user8420 |
| 011 | Attache | 180109T051858Z | Conor O& |
| 040 | Perl 6 | 140406T192932Z | Mouq |
| 033 | QBIC | 161205T173227Z | steenber |
| 072 | CasioBasic | 170512T090011Z | numberma |
| 038 | PARI/GP | 170921T041027Z | MD XF |
| 139 | Emojicode | 170730T120948Z | betseg |
| 076 | S.I.L.O.S | 170513T125436Z | Rohan Jh |
| 038 | C | 170422T160913Z | 2501 |
| 060 | Game Maker Language | 131130T144508Z | Timtech |
| 067 | TCL 8.5 | 131109T200215Z | user7795 |
| 047 | TIBasic | 170405T123735Z | pizzapan |
| 016 | 80386 assembly | 170210T010457Z | FUZxxl |
| 048 | Python repl | 130802T222254Z | boothby |
| 053 | Java 8 | 170127T112441Z | Linnea G |
| 060 | Clojure | 170118T201026Z | Carcigen |
| 053 | Java OpenJDK | 170107T035110Z | Pavel |
| 077 | Clojure | 161206T050002Z | clismiqu |
| 071 | C# | 161214T120522Z | Alfie Go |
| 054 | Python 2 | 150122T151012Z | user344 |
| 043 | Haskell | 150123T001654Z | nimi |
| 055 | R | 161205T101433Z | JAD |
| 037 | Befunge 93 | 161205T185049Z | MercyBea |
| 074 | Axiom | 161205T094506Z | user5898 |
| 040 | Befunge | 160414T073614Z | SE - sto |
| 036 | Mathcad | 160418T115534Z | Stuart B |
| 122 | Oracle SQL 11.2 | 160418T095948Z | Jeto |
| 035 | Mathematica | 130802T162539Z | miles |
| 024 | K | 150315T231020Z | JohnE |
| 034 | Perl 34 +1 chars | 130801T120459Z | primo |
| 022 | Pyth | 150529T083145Z | gcq |
| 043 | Retina | 150529T033102Z | randomra |
| 059 | This Programming Language | 150315T012556Z | BobTheAw |
| 026 | Fish 33 chars including whitespace | 140510T070723Z | TalkTake |
| 7373 | Haskell 73 Bytes 73 Chars | 140406T224258Z | Christop |
| 029 | JavaScript ES6 29 Characters | 140406T214551Z | MT0 |
| 053 | ~~! No Comment | 140404T150459Z | cjfaure |
| nan | 140404T165850Z | ɐɔıʇǝɥʇu | |
| 136 | Java | 131130T193941Z | Andrew G |
| 061 | PowerShell | 131112T044735Z | Iszi |
| 048 | C++ | 130829T001602Z | Joe Z. |
| 049 | Ruby 1.9 | 130901T133013Z | daniero |
| 047 | C | 130830T151835Z | Fors |
| 028 | Rebmu | 130814T043216Z | HostileF |
| 027 | dc | 130806T035048Z | daniero |
| 046 | Q | 130801T141254Z | tmartin |
| 094 | newLISP | 130802T121918Z | cormulli |
| 018 | GolfScript | 130801T115134Z | Volatili |
| nan | As I usually do | 130801T112246Z | Doorknob |
| 065 | F# | 130801T194221Z | Daniel |
| 126 | Java | 130801T154202Z | jsedano |
| 069 | C | 130801T163851Z | ugoren |
| 030 | J | 130801T142908Z | John Dvo |
| 031 | APL | 130801T122237Z | marinus |
| 023 | GolfScript | 130801T120813Z | Peter Ta |
Bespoke, 269 bytes
take N
a N value2K divides cleanly by twos;else,we actually triple it,adding ones
notice with one,it loops
reaching one happened generally;this is Collatzs conjecture
question:will it always continue looping it?nobody is sure
iterated counting assumes one is a lonely N
Uses the formula \$\frac{6^{n \% 2} \times n}{2} + (n \% 2)\$ to calculate the next number in the sequence, and counts along until \$n\$ is 1. (This turned out to be the same byte count as a naive approach with CONTROL IF/CONTROL OTHERWISE, but I liked these word lengths better.)
C# 10 85 66 55 bytes
The following uses top-level programs and implicit using statements, all available since C# 10.
f=n=>{var l=0;for(;n>1;l++)n=n%2<1?n/2:n*3+1;return l;}
Thanks to Themoonisacheese for providing an example: Jdoodle
However, I couldn't find a way to run C# 10 or newer in Try it Online, so I added the necessary stuff to make it run in older versions. Here goes:
Edit: Reduced to a single function.
C# 140 bytes
using System;class P{static void Main(string[] args){var n=int.Parse(args[0]);var l=0;for(;n>1;l++)n=n%2<1?n/2:n*3+1;Console.WriteLine(l);}}
Vyxal 3, 19 15 14 bytes
{D¥$‹|›£e[½|T›
Themoonisacheese tried to write an answer for this question and talked about it in the Vyxal chat, and I tried to do the same thing in order to learn this language I know nothing about. This answer follows some suggestions provided in chat, so thanks to Themoonisacheese :)
Explanation
{D¥$‹|›£e[½|T›
¥$ # Push register in advance (will be incremented or printed)
{D ‹| # While input - 1 != 0
ݣ # Increment register by 1
e[½| # If input is even, divide it by 2
T› # Else, multiply it by 3 and increment
💎
Created with the help of Luminespire.
Raku (Perl 6) (rakudo), 50 bytes
->$x {(my$n=$x,{$n=$n%2??3*$n+1!!$n/2}...2).elems}
->$x # take arg
{(my$n=$x, # make mutable
{$n=$n%2??3*$n+1!!$n/2} # collatz
...2) # lazy list of each step
.elems} # number of steps
SAKO, 83 bytes
PODPROGRAM:F(N)
I=0
1)I=I+1
D=MOD(N,2)
N=(6*D×N)/2+D
GDYN=1:2,INACZEJ1
2)F()=I
WROC
Uses the formula
where D = N mod 2 for calculating the next value in the sequence.
I don't believe this is the shortest solution, but I'm stuck and don't know how to make it shorter. (I'm probably missing something obvious.)
Full programme version, 92 bytes
CZYTAJ:N
I=0
1)I=I+1
D=MOD(N,2)
N=(6*D×N)/2+D
GDYN=1:2,INACZEJ1
2)DRUKUJ(9,0):I
STOP1
KONIEC
Reads from STDIN. For results above 10 digits long prints in E notation.
ArnoldC, 880 bytes
IT'S SHOWTIME
HEY CHRISTMAS TREE i
YOU SET US UP 0
HEY CHRISTMAS TREE l
YOU SET US UP 0
HEY CHRISTMAS TREE e
YOU SET US UP 0
HEY CHRISTMAS TREE c
YOU SET US UP 0
GET YOUR ASS TO MARS i
DO IT NOW
I WANT TO ASK YOU A BUNCH OF QUESTIONS AND I WANT TO HAVE THEM ANSWERED IMMEDIATELY
GET TO THE CHOPPER l
HERE IS MY INVITATION i
LET OFF SOME STEAM BENNET 1
ENOUGH TALK
STICK AROUND l
GET TO THE CHOPPER c
HERE IS MY INVITATION c
GET UP 1
ENOUGH TALK
GET TO THE CHOPPER e
HERE IS MY INVITATION i
I LET HIM GO 2
ENOUGH TALK
BECAUSE I'M GOING TO SAY PLEASE e
GET TO THE CHOPPER i
HERE IS MY INVITATION i
YOU'RE FIRED 3
GET UP 1
ENOUGH TALK
BULLSHIT
GET TO THE CHOPPER i
HERE IS MY INVITATION i
HE HAD TO SPLIT 2
ENOUGH TALK
YOU HAVE NO RESPECT FOR LOGIC
GET TO THE CHOPPER l
HERE IS MY INVITATION i
LET OFF SOME STEAM BENNET 1
ENOUGH TALK
CHILL
TALK TO THE HAND c
YOU HAVE BEEN TERMINATED
explained:
IT'S SHOWTIME #begin main
HEY [...]
US UP 0 #variable declarations
GET YOUR ASS TO MARS i #assign result of method call to i
DO IT NOW
I WANT TO ASK YOU A BUNCH OF QUESTIONS AND I WANT TO HAVE THEM ANSWERED IMMEDIATELY
#call method read integer
GET TO THE CHOPPER l #assign to l(oop)...
HERE IS MY INVITATION i
LET OFF SOME STEAM BENNET 1 #i>1?
ENOUGH TALK
STICK AROUND l #while l
GET TO THE CHOPPER c #c++
HERE IS MY INVITATION c
GET UP 1
ENOUGH TALK
GET TO THE CHOPPER e #e=i%2
HERE IS MY INVITATION i
I LET HIM GO 2
ENOUGH TALK
BECAUSE I'M GOING TO SAY PLEASE e #if e==1
GET TO THE CHOPPER i #i = i*3+1
HERE IS MY INVITATION i
YOU'RE FIRED 3
GET UP 1
ENOUGH TALK
BULLSHIT #else
GET TO THE CHOPPER i #i = i/2
HERE IS MY INVITATION i
HE HAD TO SPLIT 2
ENOUGH TALK
YOU HAVE NO RESPECT FOR LOGIC #endif
GET TO THE CHOPPER l #l = i>1
HERE IS MY INVITATION i
LET OFF SOME STEAM BENNET 1
ENOUGH TALK
CHILL #endwhile
TALK TO THE HAND c #print(c)
YOU HAVE BEEN TERMINATED #end main
Swift 6, 40 bytes
let e={$0<2 ?0:e($0%2<1 ?$0/2:$0*3+1)+1}
AWK, 38 bytes
{for(x=$1;x>1;$0=++i)x=x%2?1+x*3:x/2}1
{for(x=$1; # x equals input
x>1; #
$0=++i) # increment output
x=x%2?1+x*3:x/2} # collatz
1 # print $0
Jalapeño, 21 bytes
%2?ₓ{₂*3+1/2§‽{₂⇥>2,{₂⇥C₀↔
Explained
# The "Colatz" chain
%2 # Input % 2
?ₓ # If, Else
{₂ # If truthy (odd)
*3+1 # Input *3 + 1
/2 # If falsy (even), return input / 2
§ # Chain seperator
‽ # While, with input as initial state
{₂⇥>2 # The Last element of state is > 2
,{₂ # Append to the state... (Returns state , ...)
⇥C₀ # Execute the first chain (Colatz) on the last element
↔ # Return the length of the final state
Hex-Dump of Bytecode
0 1 2 3 4 5 6 7 8 9 A B C D E F
0000: 54 32 a1 c6 52 33 50 31 53 32 0a a2 c6 dc 5b 32
0010: 29 c6 dc c0 d6
Periodically, 73 bytes
yes i made this esolang recently, but it's not even good for golfing! so does it really matter?
H6I3Br2IBrO2Br3O2Ti[IKCI3SeF{OCONBrIFI}Fe{OCSiFI}CO3KI4AlO4FOI5BrCo]1I5Cl
explanation (this code is not valid)
H6 | initialize tape with 6 elements
I3Br2 | add 2 to vars[3]
IBr | add 1 to vars[4]
O2Br3 | add 3 to vars[2]
O2Ti | get user input, set it to vars[2]
[ | do...
IK | copy vars[0] to vars[1]
CI3SeF | modulo vars[1] by 2
{ | if vars[1] is 1...
OCON | multiply vars[0] by 3
Br | add 1
IFI | neutralize argument list so nothing messes up
} | ...end
Fe | apply logical NOT to vars[1]
{ | if vars[1] is 1...
OCSi | divide vars[0] by 2
FI | neutralize argument list
} | ...end
CO3K | copy vars[0] to vars[1]
I4Al | set vars[1] to the boolean result of if vars[1] != 1
O4FOI5Br | increase vars[5] by 1
Co | reset argument stuff
]1 | ...while vars[1] is true
I5Cl | print the final result (vars[5])
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
Acc!!, 127 75 70 bytes
-5 bytes thanks to Mukundan314
Count u while N {
u
}
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.)
With comments
The input method technically takes advantage of undefined behavior: the official implementation of Acc!! adds a newline character to the end of each line of input.
# Read input in unary
Count u while N { # Increment u from 0 while not EOF
u # Set accumulator to u
}
# For a unary number X, the loop will run X+1 times (including the
# trailing newline); because the loop variable starts at 0, this sets
# the accumulator to X
# 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
Uiua, 23 bytes
⧻⍢(⊂0⟨÷2|+1×3⟩◿2.|¬∊2)¤
Explain:
⧻ # length of list
⍢( | ) # do while
⊂0 # prepend 0 to the list
⟨÷2|+1×3⟩◿2. # apply collatz the the whole list
¬∊2 # while the list doesn't contain 2
¤ # arg as list
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:
Nekomata, 10 bytes
ˡ{1>ᵉ½3*→I
ˡ{1>ᵉ½3*→I
ˡ{ Repeat the following function until it fails, and count the number of steps:
1> Check if greater than 1
ᵉ Parallelly apply the following two functions:
½ 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
Thunno 2, 17 bytes
(1Q;Dɗ?3×⁺:½;ẋ)x⁻
Only works in Thunno \$\le 2.1.9\$. In versions \$\ge 2.1.10\$, ẋ can be replaced with ẋ⁺.
Explanation
(1Q;Dɗ?3×⁺:½;ẋ)x⁻ # implicit input; x is initialised to 1
(1Q; ) # while TOS != 1:
D # duplicate
ɗ? # if TOS is odd:
3×⁺ # triple and increment
: # else:
½ # halve
;ẋ # increment x
x⁻ # push x and decrement
# implicit output
Python 2, 68 58 54 52 bytes
f=lambda n:1+(n-2and f((n/2,3*n+1)[n%2]));f(input())
Thanks to @Bakuriu and @boothby for the tips :)
Gambit scheme, 106 98 characters, 40 parentheses
(let((f(lambda(x)(cond((= x 1) 0)((odd? x)(+ 1(f(+ 1(* 3 x)))))(else(+ 1(f(/ x 2))))))))(f(read)))
91 89 chars with define directly
(define(f x)(cond((= x 1)0)((odd? x)(+ 1(f(+ 1(* 3 x)))))(else(+ 1(f(/ x 2))))))(f(read))
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
brev, 71 bytes
(rec(f x)(cond((= x 1)0)((odd? x)(+(f(+(* 3 x)1))1))(1(+(f(/ x 2))1))))
Husk, 12 11 bytes
€2¡?o→*3½%2
Explanation
€2¡?o→*3½%2
¡ Infinitely iterate the following function:
? If
%2 the argument mod 2 is 1:
o Compose:
→ Increment
*3 Times three
½ Else, halve
€2 Index (1-based) of first occurrence of 2 in that infinite list
Pyth 23byte
J0WtQ=Q@,/Q2h*3QQ=JhJ;J
Pip, 23 21 19 bytes
a>1&URE[HVa3*a+1]@a
Try It Online! Note that this is a recursive solution; moderately large numbers of iterations will cause a recursion error.
Explanation
a>1&URE[HVa3*a+1]@a
a>1 Is the argument greater than 1?
& If not, return 0; if so, return
U 1 plus
RE Recursive call to the main function with this argument:
[ ] Construct a list containing two elements:
HVa Half of the argument
3*a+1 3 times the argument plus 1
@ Select the element at (modular) index of
a The argument
A non-recursive solution in 21 bytes:
Wa>1&Uia:%a?3*a+1HVai
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;
HVa else, halve a
i Autoprint i, the iteration count
The original 23-byte solution in Pip Classic is similar: Try it online!
Jelly, 12 bytes
×3‘$HḂ?ß0’?‘
How it works
×3‘$HḂ?ß0’?‘ Main link. Argument: n (integer)
Ḃ? Yield the last bit of n is 1:
$ Evaluate the three links to the left as a monadic chain:
×3 Multiply n by 3.
‘ Increment the product by 1.
H Else, halve n.
’? If n-1 is non-zero:
ß Recursively call the main link.
0 Else, yield 0.
‘ Increment the result by 1.
Alice, 26 bytes
/2:k@
.i#o3*hk
^d/.2%.j.t$
Explanation
This makes use of Alice's "jump and return" commands which allow you to implement subroutines. They're not at all separately scoped or otherwise encapsulated and nothing is stopping you from leaving the "subroutine", but if you want you can basically use them to jump to a different place in the code to do whatever you need and then continue where you left off. I'm using this to choose between two different "subroutines" depending on the parity of the current value to either halve it or triple and increment it.
To count the number of steps, we simply make a copy of the value at each step and check the stack depth at the end.
/ Reflect to SE. Switch to Ordinal.
i Read the input as a string.
/ Reflect to E. Switch to Cardinal.
. Duplicate the input.
2% Take the current value modulo 2 to get its parity.
. Duplicate it. So for even inputs we've got (0, 0) on top of the stack
and for odd inputs we've got (1,1).
j Use the top two values to jump to the specified point on the grid. That's
either the top left corner, or the cell containing the i.
Using j also pushes the original position of the IP (the cell containing j
in this case) to a separate return address stack, so we can return here
later.
Note that the IP will move before executing the first command.
Subroutine for even values:
2: Divide by 2.
k Pop an address from the return stack and jump back there (i.e. to the j).
Subroutine for odd values:
# Skip the next command (the 'o' is there for a later part of the code).
3* Multiply by 3.
h Increment.
k Pop an address from the return stack and jump back there (i.e. to the j).
Either way, we continue after the j:
. Duplicate the new value.
t Decrement it, to get a 0 if we've reached 1.
$ Skip the next value if the result was 0.
This part is run if the current value wasn't 1 yet:
^ Send the IP north.
. Duplicate the current value to increase the stack depth.
/ Reflect to SW. Switch to Ordinal.
Immediately reflect off the left boundary and move SE.
i Try to read more input, but this just pushes an empty string.
However, the next command will be the duplication . which tries to
duplicate an integer, so this empty string is immediately discarded.
After that we start the next iteration of the loop.
This part is run once the value reaches 1:
d Push the stack depth.
/ Reflect to SE. Switch to Ordinal.
Immediately reflect off the bottom boundary and move NE.
o Implicitly convert the stack depth to a string and print it.
@ Terminate the program.
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)
ngn/k, 21 bytes
#{(2|-2!x;1+3*x)2!x}\
I converted the operation to be x = max(2, x/2) so the sequence had a fixed point, and converges (\) handled the rest. # counts the number of steps, including the beginning.
C (gcc) 38, 37 bytes (thanks to @UnrelatedString)
c(x){return~-x?-~c(x%2?3*x+1:x/2):0;}
First recursive solution that came to mind. Fairly simple. Explanation (ungolfed):
int c() {
return~-x? //If x!=1
-~c(x%2?3*x+1:x/2) // Compute the next term and recurse on that term. Add 1.
:
0; //Base case
}
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.
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)
LOLCODE, 217 bytes
HAI 1
I HAS A N
GIMMEH N
I HAS A C
IM IN YR L UPPIN YR D WILE DIFFRINT N 1
BOTH SAEM MOD OF N 2 0,O RLY?
YA RLY,N R QUOSHUNT OF N 2
NO WAI,N R SUM OF PRODUKT OF N 3 1
OIC
C R D
IM OUTTA YR L
VISIBLE SUM OF C 1
KTHXBYE
rusty_deque, 85 bytes
{dup~{3~*~1~+~}~{2~swap~/~}~{dup~2~swap~%~0~=~}~ite~}~{dup~1~<~}~while~pop~len~lb~ll~
Explanation
# start with n on the right of the deque
{ # begin while block
dup~ # dup to get next step
{3~*~1~+~}~ # when n is odd, push 3*n+1
{2~swap~/~}~ # when n is even, push n/2
{dup~2~swap~%~0~=~}~ # conditional, is n even?
ite~ # if
}~ # end while block
{dup~1~<~}~ while~ # while n > 1
pop~ # delete extra 1
len~ lb~ # convert the stack to a list
ll~ # pop list, push len of list
Rust, 67 bytes
|mut n|{let mut u=0;while n!=1{if n%2==0{n/=2}else{n=3*n+1}u+=1}u};
Nice way of practicing rust
Julia 0.6, 29 27 bytes
!n=n>1&&1+!(n%2>0?3n+1:n/2)
I can't seem to compile Julia 0.1 on my machine, so there's a chance this is non-competing.
Julia, 54 chars
f(n,i)=n==1 ? i : n%2==0 ? f(n/2,i+=1) : f(n*3+1,i+=1)
Julia, 45 chars
>(n,i=0)=n<2 ? i : n%2<1 ? n/2>i+1 : 3n+1>i+1
Thanks to the brilliant suggestion by MarcMush!
x86 machine code, 15 bytes
xxd -g1:
00000000: 99 42 8d 4c 40 01 d1 e8 0f 42 c1 75 f4 4a c3 .B.L@....B.u.J.
Commented assembly (NASM syntax):
[bits 32]
global collatz
; input: eax, assumed positive and > 1
; output: edx
; clobbers: eax, ecx, edx
collatz:
cdq ; count = 0 (abuses eax > 1)
.Lloop:
inc edx ; increment count
lea ecx, [eax+2*eax+1] ; tmp = 3*n + 1
shr eax, 1 ; n = n / 2, sets flags
cmovc eax, ecx ; swap with 3n+1 if it was originally odd (does not set flags)
jnz .Lloop ; shr also sets ZF if the shr result was zero, end condition
dec edx ; Correct the off by one
ret ; return
Try it online! (converted to GAS Intel syntax and wrapped in C++)
Notes
The way this works is by using shr magic, allowing me to calculate n/2 and also test if n was originally odd (CF=1) or originally 1 (ZF=1).
Unfortunately, this results in an off by one since it will run when n == 1, but it is correctable via a simple dec.
Note that while this is larger than the other x86 solution, the other solution is a snippet, not a complete function, and it doesn't even count the steps, only calculating the sequence.
If that version were to count the steps, while it would be more efficient, it would be larger because the bsr complicates the bookkeeping, unless I can be proven otherwise.
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.
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
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.
HBL, 16 15 bytes
?(%.)(+(*.<))(/.2
?(-.)(-+?().
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)))
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
><>, 28 bytes
:1=?v::2%?v2,
+c0.\l1-n;\3*1
This takes input from the stack, computes the different steps on the stack, then returns its size when 1 is reached.
Improved version by JoKing, 24 bytes :
:1=?\::2%b$.2,
3*1+\~ln;
BitCycle -u, 90 bytes
~ ~!
?v C/v
v< <
A\\ B^
>/\/C =v
Cvv <
v~v/
> ^
v =
>> >>^
\~~~
~v~^
^ + ~
Try it online! Or, watch it in action here.
Algorithm
The main loop starts with the current number \$n\$ in unary in the A collector. We divide the number by 2, splitting off two bits at a time; one of the halves, \$\lfloor \frac n 2 \rfloor\$, goes into the uppermost C collector; the other half goes into the middle C collector; and the remainder, \$n\text{ mod }2\$, goes into the bottom C collector.
Once the number is completely divided up in this way, the C collectors open.
- The top C collector sends a 1 to the sink at the top right, adding 1 to the output, and sends all of its bits back into A.
- If the bottom C collector is empty (i.e. \$n\text{ mod }2 = 0\$, i.e. \$n\$ was even), the first bit from the middle collector hits the bottommost switch
=and activates it pointing right, which discards the bits. This leaves A with just the \$\lfloor\frac n 2\rfloor\$ bits it got from the top C collector: \$n\text{ even}\to n/2\$. - If the bottom C collector contains a 1 bit (i.e. \$n\text{ mod }2 = 1\$, i.e. \$n\$ was odd), a negated copy of it hits the bottommost switch and activates it pointing left. This sends the bits from the bottom and middle C collectors into the big collection of dupnegs
~at the bottom, which makes five copies of its input and discards one bit. All the copies are then sent back into A: \$n\text{ odd}\to \lfloor\frac n 2\rfloor + 5\left( \lfloor\frac n 2\rfloor + 1\right) - 1 = 6\lfloor\frac n 2\rfloor + 3 + 1 = 3n + 1\$.
This whole process repeats until \$n=1\$, at which point the two halves are 0; this means the only C collector with data is the bottommost one that holds the remainder. The remainder bit is directed up to the uppermost switch =. Normally, this switch would have been activated by the bits from the middle C collector already, and the remainder bit would follow them into the 5-times circuitry. But since the middle C collector is empty, the remainder bit passes through the switch and continues northward off the playfield. Since there are no bits remaining on the playfield, the program halts and displays the number of steps taken.
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)
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
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.
Forth (gforth), 71 bytes
: f begin dup 2 mod if 3 * 1+ else 2/ then dup dup 1 = until depth 1- ;
Uses an until loop, and computes stack depth -1.
Forth (gforth), 76 bytes
: f dup dup 1 = if 0 else 2 mod if 3 * 1+ else 2/ then dup recurse 1+ then ;
A recursive function.
Haskell, 47 bytes
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.
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.
FRACTRAN, 8 fractions (45 bytes)
$$\frac{5120}{33}, \frac{15}{11}, \frac{22}{105}, \frac{33}{560}, \frac{13}{5}, \frac{3}{2}, \frac{7}{9}, \frac{11}{7}$$
Takes input as \$3^n\$; halts at \$3 \cdot 13^m\$ for a sequence with \$m\$ iterations.
How it works
If the current state is \$3^n \cdot 13^m\$, if \$n = 1\$, the program halts immediately; if \$n = 2k\$ is even, we have
$$\begin{multline*}3^{2k} \cdot 13^m \xrightarrow{\left(\frac{7}{9}\right)^k} 7^k \cdot 13^m \xrightarrow{\frac{11}{7}} 7^{k - 1}\cdot 11 \cdot 13^m \xrightarrow{\frac{15}{11}} 3 \cdot 5 \cdot 7^{k - 1} \cdot 13^m \\ \xrightarrow{\left(\frac{22}{105} \cdot \frac{15}{11}\right)^{k - 1}} 2^{k - 1} \cdot 3 \cdot 5 \cdot 13^m \xrightarrow{\frac{13}{5}} 2^{k - 1} \cdot 3 \cdot 13^{m + 1} \xrightarrow{\left(\frac{3}{2}\right)^{k - 1}} 3^k \cdot 13^{m + 1};\end{multline*}$$
and if \$n = 2k + 1\$ is odd, we have
$$\begin{multline*} 3^{2k + 1} \cdot 13^m \xrightarrow{\left(\frac{7}{9}\right)^k} 3 \cdot 7^k \cdot 13^m \xrightarrow{\frac{11}{7}} 3 \cdot 7^{k - 1} \cdot 11 \cdot 13^m \xrightarrow{\frac{5120}{33}} 2^{10} \cdot 5 \cdot 7^{k - 1} \cdot 13^m \\ \xrightarrow{\left(\frac{33}{560} \cdot \frac{5120}{33}\right)^{k - 1}} 2^{6k + 4} \cdot 5 \cdot 13^m \xrightarrow{\frac{13}{5}} 2^{6k + 4} \cdot 13^{m + 1} \xrightarrow{\left(\frac{3}{2}\right)^{6k + 4}} 3^{6k + 4} \cdot 13^{m + 1},\end{multline*}$$
where \$6k + 4 = 3n + 1\$.
FRACTRAN, 24 fractions
Uses 180 bytes, for the more conventional counters...
68/13, 133/102, 341/51, 115/17, 17/19, 87/161, 17/23, 23/29, 53/93,
26973/217, 410/259, 43/111, 976/37, 37/41, 329/215, 37/43, 43/47,
118/265, 1/53, 53/59, 67/305, 1/61, 61/67, 117/4
Explanation
Am a bit lazy to add an explanation now; happy to do so if it gets attention/upvotes! However, I do have some notes for when I first wrote up the Collatz Conjecture code which you can run here. It's almost the same, but the TIO command line arguments are set to print every number in the sequence along the way, which makes it less of a blackbox!
State Diagrams for COLLATZGAME
Here are the state diagrams, for which I used Conway's original notation which he presents in this article.
Change Made
The above is simply to calculate the Collatz sequence for n given an input of the form 2^n. The only change I made to also keep count of the steps taken was to make the 1/3 from states Q -> D into an 11/3, 11 being the smallest unused prime. This fraction is only executed once for every number in the sequence; it's the state that figures out whether the number is even or odd to figure out what's next. Therefore, the 11 prime register is incremented once per number in the sequence, except one, yielding the number of steps.
Note
I simply encoded the state diagram as below and wrote an interpreter which did the dirty work. However, the work done to convert a state diagram to FRACTRAN is also detailed in Conway's article above:
- A: 9/4 -> T
- T: 4/1 -> Q
- Q: 7/6*, 11/3 -> D, 5/1 -> R
- R: 3/7*|Q
- D: 1/3 -> E, 729/7 -> M
- M: 10/7*, 1/3 -> N, 16/1 -> O
- N: 7/5*|M
- E: 2/5*|A
- O: 1/5*|A
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
}
SmileBASIC, 54 bytes
INPUT N
WHILE N-1D=1AND N
C=C+1N=N*3*D+D+N/2*!D
WEND?C
Aceto, 33 bytes
&)
(I2/(I)&
+3_!
1*2%
i@d|(
rd1=p
Explanation:
Read an integer:
i
r
Set a catch point, duplicate the number and check if it's 1, if so, we mirror horizontally (meaning we end up on the ( next to the |):
@ |
d1=
Duplicate the value again, check if it's divisible by 2, if so, we mirror vertically (ending up on the 2 above):
_!
2%
Otherwise, multiply by 3, add 1, go one stack to the left, increment the number there (initially zero), go back to the original stack, and raise (jumping back to the catch point):
&)
(I
+3
1*
If it was divisible, we divide the number by two, and again increment the stack to the left and jump to the catch point:
2/(I)&
When the number is 1 after jumping to the catch point, we go to the left stack and print that number (and exit):
(
p
05AB1E, 16 15 bytes
-1 byte thanks to Kevin Cruijssen
[Éi3*>ë2÷}¼Ð#]¾
Explanation
# Implicit input: integer n
[ ] # Infinite loop
i } # if:
É # n is odd
3*> # compute 3n+1
ë # else:
2÷ # compute n//2
¼ # increment counter variable
Ð # Triplicate
# # Break loop if n = 1
¾ # output counter variable
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
><>, 27 26 23 bytes
\ln;
\::2%:@5*1+2,*+:2=?
Like the other ><> answers, this builds the sequence on the stack. Once the sequence reaches 2, the size of the stack is the number of steps taken.
Thanks to @Hohmannfan, saved 3 bytes by a very clever method of computing the next value directly. The formula used to calculate the next value in the sequence is:
$$f(n)=n\cdot\frac{5(n\bmod2)+1}{2}+(n\bmod2)$$
The fraction maps even numbers to 0.5, and odd numbers to 3. Multiplying by n and adding n%2 completes the calculation - no need to choose the next value at all!
Edit 2: Here's the pre-@Hohmannfan version:
\ln;
\:::3*1+@2,@2%?$~:2=?
The trick here is that both 3n+1 and n/2 are computed at each step in the sequence, and the one to be dropped from the sequence is chosen afterwards. This means that the code doesn't need to branch until 1 is reached, and the calculation of the sequence can live on one line of code.
Edit: Golfed off another character after realising that the only positive integer that can lead to 1 is 2. As the output of the program doesn't matter for input < 2, the sequence generation can end when 2 is reached, leaving the stack size being the exact number of steps required.
Previouser version:
\~ln;
\:::3*1+@2,@2%?$~:1=?
MathGolf, 7 bytes
kÅ■┐▲î
Don't get fooled, there's a non-breaking space at the end of the program.
Explanation
k Read input as integer
Å Start a block of length 2
■ Map TOS to the next item in the collatz sequence
┐ Push TOS-1 without popping
▲ Do block while TOS is true
î Push the length of the last loop
Discard everything but top of stack
MathGolf, 14 bytes (no built-ins, provided by JoKing)
{_¥¿É3*)½┐}▲;î
Explanation
{ Start block of arbitrary length
_ Duplicate TOS
¥ Modulo 2
¿ If-else (works with TOS which is 0 or 1 based on evenness)
É3*) If true, multiply TOS by 3 and increment
½ Otherwise halve TOS
┐ Push TOS-1 (making the loop end when TOS == 1)
}▲ End block, making it a do-while-true with pop
; Discard TOS
î Print the loop counter of the previous loop (1-based)
Ideally, this solution could become 13 bytes, since it's not neccessary to have the ending of the block be explicit when the loop type instruction comes right after. I'll see when I get around to coding implicit block ending when loop type is present.
Jelly, 10 bytes
×3‘ƊHḂ?Ƭi2
How it works
×3‘ƊHḂ?Ƭi2 Main link (monad). Input: integer >= 2
? Create a "ternary-if" function:
Ḃ If the input is odd,
×3‘Ɗ compute 3*n+1;
H otherwise, halve it.
Ƭ Repeat until results are not unique; collect all results
i2 Find one-based index of 2
Example: The result of ...Ƭ for input 5 is [5, 16, 8, 4, 2, 1]. The one-based index of 1 is 6, which is 1 higher than expected. So we choose the index of 2 (which is guaranteed to come right before 1) instead.
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(...)
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
}
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.
MATL, 21 16 bytes
Saved 5 bytes thanks to Luis Mendo! I didn't know while had a finally statement that could be used to get the iteration index. Keeping track of the number of iterations took a lot of bytes in my original submission.
`to?3*Q}2/]tq}x@
Explanation:
`t % grab input implicitly and duplicate it.
% while ...
o? % the parity is `1` (i.e. the number is odd
3*Q % multiply it by 3 and increment it
} % else
2/ % divide it by 2
] % end if
tq % Duplicate the current value and decrement it
} % Continue loop if this value is not zero (i.e. the current value is >1
x % Else, delete the current value (the 0)
@ % And output the "while index" (i.e. the number of iterations)
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.
Emojicode, 157 bytes
🐖🎅🏿➡️🔡🍇🍮a🐕🍮c 0🔁▶️a 1🍇🍊😛🚮a 2 0🍇🍮a➗a 2🍉🍓🍇🍮a➕✖️a 3 1🍉🍮c➕c 1🍉🍎🔡c 10🍉
Explanation:
🐋🚂🍇
🐖🎅🏿➡️🔡🍇
🍮a🐕 👴 input integer variable 'a'
🍮c 0 👴 counter variable
🔁▶️a 1🍇 👴 loop while number isn’t 1
🍊😛🚮a 2 0🍇 👴 if number is even
🍮a➗a 2 👴 divide number by 2
🍉
🍓🍇 👴 else
🍮a➕✖️a 3 1 👴 multiply by 3 and add 1
🍉
🍮c➕c 1 👴 increment counter
🍉
🍎🔡c 10 👴 return final count as string
🍉
🍉
🏁🍇
😀🎅🏿 16
🍉
Java (OpenJDK 8), 54 bytes
a->{int c=0;for(;a!=1;c++)a=a%2>0?a*3+1:a/2;return c;}
This answer is a little to simple to justify an explanation, it’s just a while loop and a ternary expression.
dc, 30 28 bytes
?[d5*2+d2%*+2/d1<f1+]dsfx1-p
This uses the formula from Jo King's answer, slightly adapted so we dup after adding 2.
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
Previous answer: 30 bytes
?[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
Hexagony, 48 44 bytes
?(]$_)"){{?{*')}/&!/={:<$["/>&_(.<@2'%<>./>=
Expanded:
? ( ] $ _
) " ) { { ?
{ * ' ) } / &
! / = . { < $ [
" / > & _ ( . < @
2 ' % < > : / >
= . . . . . .
. . . . . .
. . . . .
Note that this fails on 1 for uhh... reasons. Honestly, I'm not really sure how this works anymore. All I know is that the code for odd numbers is run backwards for even numbers? Somehow?
The new version is much cleaner than the previous, but has a few more directionals in comparison and also ends in a divide-by-zero error. The only case it doesn't error is when it actually handles 1 correctly.
Ruby, 35 bytes
f=->n{n<2?0:1+f[n*3/(6-5*w=n%2)+w]}
How it works
Instead of getting the 2 values and choosing one, multiply by 3, divide by 1 if odd, or 6 if even, and then add n modulo 2.
Add++, 50 bytes
D,f,@,dd2/i@3*1+$2%D
+?
-1
W,+1,$f>x,},+1,},-1
}
O
-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;
Befunge-93, 29 bytes
&<\+1\/2+*%2:+2*5:_$#-.#1@#:$
A nice and concise one-liner. This uses the formula (n+(n*5+2)*(n*5%2))/2 to calculate the next number in the series.
brainfuck, 59 56 bytes
,-[<->[[>]+<[-<]>>]>[-<<[++>+<]>->]<<[+>+++<]<<+>>>]<<<.
Try it online! (Slightly modified for ease of use)
Input and output as character codes. This is more useful with arbitrarily sized cells, but can still work with small values in limited cell sizes.
How It Works
Tape Format:
Counter 0 Copy Number Binary...
^End ^Start
,-[ Get input, decrement by 1 and start loop
<-> Initialises the copy of the value at -1
[[>]+<[-<]>>] Converts the input to binary while preserving a negative copy
<+>>[-<<[++>+<]>->] If the last digit of the binary is 1 (n-1 is odd), divide by 2 and decrement
<<[+>+++<] If the last digit of the binary is 0 (n-1 is even), multiply by 3
<<+>>> Increment counter and end on n-1
]<<<. End loop and print counter
Brachylog, 16 bytes
1b|{/₂ℕ|×₃+₁}↰+₁
Explanation
Either:
1 The input is 1.
b In which case we unify the output with 0 by beheading the 1
(which removes the leading digit of the 1, and an "empty integer"
is the same as zero).
| Or:
{ This inline predicate evaluates a single Collatz step on the input.
Either:
/₂ Divide the input by 2.
ℕ And ensure that the result is a natural number (which is
equivalent to asserting that the input was even).
| Or:
×₃+₁ Multiply the input by 3 and add 1.
}
↰ Recursively call the predicate on this result.
+₁ And add one to the output of the recursive call.
An alternative solution at the same byte count:
;.{/₂ℕ|×₃+₁}ⁱ⁾1∧
;. The output of this is a pair [X,I] where X is the input and
I will be unified with the output.
{/₂ℕ|×₃+₁} This is the Collatz step predicate we've also used above.
ⁱ⁾ We iterate this predicate I times on X. Since we haven't actually
specified I, it is still a free variable that Brachylog can backtrack
over and it will keep adding on iterations until the next
constraint can be satisfied.
1 Require the result of the iteration to be 1. Once this is
satisfied, the output variable will have been unified with
the minimum number of iterations to get here.
∧ This AND is just used to prevent the 1 from being implicitly
unified with the output variable as well.
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
Stax, 12 bytesCP437
ÄFl,rBoU¡£&╦
14 bytes when unpacked,
1{h_3*^\_@gt%v
Adaptation of https://github.com/tomtheisen/stax/blob/master/testspecs/golf/CollatzTest.staxtest .
Wumpus, 22 bytes
I]=2:~3*)=&~~!0~.
l(O@
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
iterations) this pushes 0 instead.
] 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@
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))
Python 2, 38 37 bytes
f=lambda n:n<3or-~f([n/2,n*3+1][n%2])
Thanks to @user84207 for a suggestion that saved 1 byte!
Note that this returns True instead of 1.
Emacs/Common Lisp, 61 bytes
(defun f(n)(if(= 1 n)0(1+(f(if(oddp n)(1+(* 3 n))(/ n 2))))))
alternatively:
(defun f(n)(if(= 1 n)0(1+(f(if(oddp n)(+ n n n 1)(/ n 2))))))
Perl 6, 40 bytes
Recursive function method, as per Valentin CLEMENT and daniero: 40 characters
sub f(\n){n>1&&1+f n%2??3*n+1!!n/2}(get)
Lazy list method: 32 characters
+(get,{$_%2??$_*3+1!!$_/2}...^1)
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
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
PARI/GP, 38 bytes
a(n)=if(n==1,0,a(if(n%2,3*n+1,n/2))+1)
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;
}
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
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.
C, 38 bytes
g(v){return v^1?1+g(v&1?v*3+1:v/2):0;}
Game Maker Language, 63 61 60 bytes
Make script/function c with this code and compile with uninitialized variables as 0:
a=argument0while(a>1){i++if i mod 2a=a*3+1else a/=2}return i
Call it with c(any number) and it will return how many times it took to become 1.
TCL 8.5 (71 70 68) (67)
TCL has no real chance of ever winning, but it is a fun way to oil the machine:
proc c x {while \$x>1 {set x [expr $x%2?3*$x+1:$x/2];incr k};set k}
formatted for readability:
proc c x {
while {$x>1} {
set x [expr $x%2 ? 3*$x+1 : $x/2]
incr k
}
set k
}
Edits: many suggestions (inspired) by sergiol. I guess the answer is more theirs than mine, by now :-)
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
80386 assembly, 16 bytes
This example uses AT&T syntax and the fastcall calling convention, the argument goes into ecx:
collatz:
or $-1,%eax # 3 bytes, eax = -1;
.Loop: inc %eax # 1 byte, eax += 1;
lea 1(%ecx,%ecx,2),%edx # 4 bytes, edx = 3*ecx + 1;
shr %ecx # 2 bytes, CF = ecx & 1;
# ecx /= 2;
# ZF = ecx == 0;
cmovc %edx,%ecx # 3 bytes, if (CF) ecx = edx;
jnz .Loop # 2 bytes, if (!ZF) goto .Loop;
ret # 1 byte, return (eax);
Here are the resulting 16 bytes of machine code:
83 c8 ff 40 8d 54 49 01 d1 e9 0f 42 ca 75 f4 c3
Python repl, 48
I'm not convinced that there isn't a shorter expression than n=3*n+1;n/=1+n%2*5;. I probably found a dozen different expressions of all the same length...
i=0
n=input()
while~-n:n=3*n+1;n/=1+n%2*5;i+=1
i
edit: I've found another solution that will never contend, but is too fun not to share.
s='s'
i=s
n=i*input()
while 1:
while n==n[::2]+n[::2]:i+=s;n=n[::2]
if n==s:i.rindex(s);break
n=3*n+s
i+=s
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);
Clojure, 60 bytes
(fn c[n](if(= n 1)0(inc(c(if(even? n)(/ n 2)(+(* n 3)1))))))
Pretty standard. Recursive function that recurses when n isn't equal to one. Each iteration, one is added to the accumulator via inc.
While this uses unoptimized recursion, I'm currently testing to see when it fails. It's at 1711000000, and is still going. The highest number of steps I've seen so far is 1008, so I don't expect it to fail anytime soon.
Pregolfed:
(defn collatz-conj [n]
(if (= n 1)
0 ; Base case
(inc ; Add one to step
(collatz-conj ; Recurse
(if (even? n) ; The rest should be be self-explanatory
(/ n 2)
(+ (* n 3) 1))))))
Clojure, 77 bytes
#(loop[x % a 0](if(= x 1)a(recur(if(=(mod x 2)0)(/ x 2)(+(* x 3)1))(inc a))))
Defines an anonymous function. Usage is like so:
(#(...) {num})
Ungolfed:
(defn collatz [n]
(loop [x n
a 0]
(if (= x 1) a
(recur (if (= (mod x 2) 0) (/ x 2) (+ (* x 3) 1)) (inc a)))))
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);}
Python 2, 59 57 55 54 bytes
i=0;n=input()
while~-n:n=[n/2,n*3+1][n%2];i+=1
print i
Haskell, 43 Bytes
c 1=0
c x|odd x=1+c(3*x+1)|1<2=1+c(x`div`2)
Usage: c 7-> 16
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.
Befunge 93, 37 bytes
&>:1-|
\@#-1<+2_.#
v#%2:<+1*3:_
<v/2:
Explanation:
& Take integer input
>:1-| If the top of the stack is 1, go to the 2nd line.
Else, go the third.
----------------------------------------------
\ -1<+2_ The top of the stack is 1, which becomes the counter for
the stack size. If the second-to-the-top of the stack is
non-zero, consume that value and increment the counter by 1.
@ . If the second-to-the-top of the stack is 0, i.e. there are
no elements besides the counter, output the counter and
terminate the program.
----------------------------------------------
v#%2:< _ The top of the stack is non-zero. Check if the top of
the stack is divisible by 2, and execute 1 of the
following accordingly:
+1*3: The top of the stack (a) is odd, so push 3a + 1,
and check the top mod 2 again.
<v/2: The top of the stack (a) is even, so push a / 2,
and check if the top is 1 again.
Like other programs, this pushes each iteration onto the stack until the top is 1, and outputs the stack size - 1.
I was able to make this program shorter by not testing if the top was 1, if the previous iteration was odd. Also, in counting the stack size, I used the fact that the top of the stack will always be 1.
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
Befunge, 42 40 bytes
Surprisingly short to be an esolang! I thank @Sok for showing how to avoid one extra branching in his answer. Saved 2 bytes after a complete rewriting of the code.
0&>\1+\:2/\:3v
.$<v_v#%2\+1*<@
`!|>\>$:1
Original answer:
1&>:2%v>2v
^\+1*3_^ /
>+v v`1:<
^1\#\_$.@
Shold be compatible with both Befunge 93 and Befunge 98. Interpretor available here.
There is no need for a trailing white space after @, so I count it as 42. However, 2D languages are often counted by their bounding box.
Mathcad, 36 "bytes"
From user perspective, Mathcad is effectively a 2D whiteboard, with expressions evaluated from left-to-right,top-to-bottom. Mathcad does not support a conventional "text" input, but instead makes use of a combination of text and special keys / toolbar / menu items to insert an expression, text, plot or component. For example, type ":" to enter the definition operator (shown on screen as ":=") or "ctl-]" to enter the while loop operator (inclusive of placeholders for the controlling condition and one body expression). What you see in the image above is exactly what appears on the user interface and as "typed" in.
For golfing purposes, the "byte" count is the equivalent number of keyboard operations required to enter an expression.
Oracle SQL 11.2, 122 bytes
WITH v(n,i)AS(SELECT:1,0 FROM DUAL UNION ALL SELECT DECODE(MOD(n,2),0,n/2,n*3+1),i+1 FROM v WHERE n>1)SELECT MAX(i)FROM v;
Un-golfed :
WITH v(n,i)AS -- Recursive view, n=>current value, i=>iterations count
(
SELECT :1,0 FROM DUAL -- Initialize with parameter and 0 iteration count
UNION ALL
SELECT DECODE(MOD(n,2),0,n/2,n*3+1),i+1 -- Compute the next value
FROM v WHERE n>1 -- End when it reaches 1
)
SELECT MAX(i)FROM v -- Return only the last iteration count
Mathematica (35)
If[#>1,#0@If[OddQ@#,3#+1,#/2]+1,0]&
Usage:
If[#>1,#0[If[OddQ@#,3#+1,#/2]]+1,0]&@16
>> 4
K, 24 bytes
#1_(1<){(x%2;1+3*x)x!2}\
With test cases:
(#1_(1<){(x%2;1+3*x)x!2}\)'2 16 5 7
1 4 5 16
This uses a bit of a cute trick to avoid conditionals- (x%2;1+3*x) builds a list of the potential next term and then the parity calculated by x!2 indexes into that list. Otherwise it's a straightforward application of the "do while" form of \, given the tacit predicate (1<) (while greater than 1) as a stopping condition:
(1<){(x%2;1+3*x)x!2}\5
5 16 8 4 2 1
The example output indicates that we need to drop the first (1_) of this sequence before taking the count (#). This is slightly shorter than taking the count and then subtracting one.
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
Pyth 27 23 22 chars
W>Q1=hZ=Q?h*Q3%Q2/Q2)Z
Pyth is much newer than the challenge and therefore won't count as a winning candidate
Retina, 43 bytes
11
2
(2+)1
$1$1$0$0$0$0
2.*
$0x
)`2
1
1?x
1
Takes input and prints output in unary.
Each line should go to its own file. 1 byte per extra file added to byte-count.
You can run the code as one file with the -s flag. E.g.:
> echo -n 1111111|retina -s collatz
1111111111111111
The algorithm is a loop of doing a Collatz step with the unary number and adding a new step-marker x at the end of the string if the number isn't 1.
When the loop ends with 1, we convert the markers to a unary number (removing the leading 1) which is the desired output.
This Programming Language, 59
v>v>_1=?v_2%?v2/ v
}0" >~"i;>3*1+v
>^>^ "+1"<
Not the shortest, but an interesting program nonetheless.
Fish (33 chars including whitespace, 26 without)
:2%?v:2, >:1=?v
>:3*1+^;nl~<
The whitespace is necessary for it to function, as ><> is a 2D language. Example run:
$ python3 fish.py collatz.fish -v 176
18
Haskell 73 Bytes 73 Chars
r n |even n=n`quot`2
|otherwise=3*n+1
c=length.takeWhile(/=1).iterate r
JavaScript (ES6) - 29 Characters
f=x=>x>1?f(x%2?x*3+1:x/2)+1:0
Creates a function f which accepts a single argument and returns the number of iterations.
JavaScript - 31 Characters
for(c=0;n>1;n=n%2?n*3+1:n/2)++c
Assumes that the input is in the variable n and creates a variable c which contains the number of iterations (and will also output c to the console as its the last command).
~-~! (No Comment) - 71 53
This language is obviously not the best for golfing since it lacks a large amount of native functionality, but that's the beauty of it.
'=|*;~~[*,~~~-~]*/~~|:''=|'''==~[*]'''='&''':''&*+~|:
First, set ''' to your input. The function '' can then be called with % as it's input and will return the answer, like so:
'''=~~~~~:''&%:
This will return ~~~~~. It actually works for n==1 (it loops forever with n==0).
As always with this language, untested.
Python (73):
Can probably be golfed a heck of a lot more.
i=0
while 1:
i+=1;j=i;k=0
while j!=1:j=(j/2,j*3+1)[j%2];k+=1
print i,k
Java (136)
public class C {public static void main(String[] a) {int i=27,c=0;while(i!=1;{c++;if(i%2==0)i/=2;else i=3*i+1;}System.out.println(c);}}
Just change the value of i to the input. For 27, it prints 111 to the console.
Whitespace view:
public class C {
public static void main(String[] a) {
int i=27,c=0;
while(i!=1) {
c++;
if(i%2==0)
i/=2;
else
i=3*i+1;
}
System.out.println(c);
}
}
I know it isn't the shortest, but I figured I'd give it a whirl. Any suggestions would be appreciated. ;)
I have to say I'm a little envious of all those who know the short languages. I'd love to see this done in Brainf**k.
PowerShell: 77 74 71 70 61
Golfed code:
for($i=(read-host);$i-ne1;$x++){$i=(($i/2),(3*$i+1))[$i%2]}$x
Notes:
I originally tried taking the user input without forcing it to an integer, but that broke in an interesting way. Any odd inputs would process inaccurately, but even inputs would work fine. It took me a minute to realize what was going on.
When performing multiplication or addition, PowerShell treats un-typed input as a string first. So, '5'*3+1 becomes '5551' instead of 16. The even inputs behaved fine because PowerShell doesn't have a default action for division against strings. Even the even inputs which would progress through odd numbers worked fine because, by the time PowerShell got to an odd number in the loop, the variable was already forced to an integer by the math operations anyway.
Thanks to Danko Durbic for pointing out I could just invert the multiplication operation, and not have to cast
read-hostto int since PowerShell bases its operations on the first object.
PowerShell Golfer's Tip: For some scenarios, like this one, switch beats if/else. Here, the difference was 2 characters.
Protip courtesy of Danko Durbic: For this particular scenario, an array can be used instead of
switch, to save 8 more characters!
There's no error checking for non-integer values, or integers less than two.
If you'd like to audit the script, put ;$i just before the last close brace in the script.
I'm not sure exactly how well PowerShell handles numbers that progress into very large values, but I expect accuracy is lost at some point. Unfortunately, I also expect there's not much that can be done about that without seriously bloating the script.
Ungolfed code, with comments:
# Start for loop to run Collatz algorithm.
# Store user input in $i.
# Run until $i reaches 1.
# Increment a counter, $x, with each run.
for($i=(read-host);$i-ne1;$x++)
{
# New $i is defined based on an array element derived from old $i.
$i=(
# Array element 0 is the even numbers operation.
($i/2),
# Array element 1 is the odd numbers operation.
(3*$i+1)
# Array element that defines the new $i is selected by $i%2.
)[$i%2]
}
# Output $x when the loop is done.
$x
# Variable cleanup. Don't include in golfed code.
rv x,i
Test cases:
Below are some samples with auditing enabled. I've also edited the output some for clarity, by adding labels to the input and final count and putting in spacing to set apart the Collatz values.
---
Input: 2
1
Steps: 1
---
Input: 16
8
4
2
1
Steps: 4
---
Input: 5
16
8
4
2
1
Steps: 5
---
Input: 7
22
11
34
17
52
26
13
40
20
10
5
16
8
4
2
1
Steps: 16
---
Input: 42
21
64
32
16
8
4
2
1
Steps: 8
---
Input: 14
7
22
11
34
17
52
26
13
40
20
10
5
16
8
4
2
1
Steps: 17
---
Input: 197
592
296
148
74
37
112
56
28
14
7
22
11
34
17
52
26
13
40
20
10
5
16
8
4
2
1
Steps: 26
---
Input: 31
94
47
142
71
214
107
322
161
484
242
121
364
182
91
274
137
412
206
103
310
155
466
233
700
350
175
526
263
790
395
1186
593
1780
890
445
1336
668
334
167
502
251
754
377
1132
566
283
850
425
1276
638
319
958
479
1438
719
2158
1079
3238
1619
4858
2429
7288
3644
1822
911
2734
1367
4102
2051
6154
3077
9232
4616
2308
1154
577
1732
866
433
1300
650
325
976
488
244
122
61
184
92
46
23
70
35
106
53
160
80
40
20
10
5
16
8
4
2
1
Steps: 106
---
Input: 6174
3087
9262
4631
13894
6947
20842
10421
31264
15632
7816
3908
1954
977
2932
1466
733
2200
1100
550
275
826
413
1240
620
310
155
466
233
700
350
175
526
263
790
395
1186
593
1780
890
445
1336
668
334
167
502
251
754
377
1132
566
283
850
425
1276
638
319
958
479
1438
719
2158
1079
3238
1619
4858
2429
7288
3644
1822
911
2734
1367
4102
2051
6154
3077
9232
4616
2308
1154
577
1732
866
433
1300
650
325
976
488
244
122
61
184
92
46
23
70
35
106
53
160
80
40
20
10
5
16
8
4
2
1
Steps: 111
---
Input: 8008135
24024406
12012203
36036610
18018305
54054916
27027458
13513729
40541188
20270594
10135297
30405892
15202946
7601473
22804420
11402210
5701105
17103316
8551658
4275829
12827488
6413744
3206872
1603436
801718
400859
1202578
601289
1803868
901934
450967
1352902
676451
2029354
1014677
3044032
1522016
761008
380504
190252
95126
47563
142690
71345
214036
107018
53509
160528
80264
40132
20066
10033
30100
15050
7525
22576
11288
5644
2822
1411
4234
2117
6352
3176
1588
794
397
1192
596
298
149
448
224
112
56
28
14
7
22
11
34
17
52
26
13
40
20
10
5
16
8
4
2
1
Steps: 93
---
Interesting bits about the input numbers which are not from the question's test cases:
14and197are Keith Numbers31is a Mersenne Prime6174is Kaprekar's Constant- And lastly, I just like
8008135. And Numberphile, obviously.
C++ (51 48)
This is a recursive function that does this; input reading comes separately.
int c(n){return n==1?0:1+(n%2?c(n*3+1):c(n/2));}
I'm sure I can do some sort of "and/or" trick with the == 0 stuff, but I have no idea how.
Ruby 1.9, 49 characters
Rubyfied Valentin CLEMENT's Python answer, using the stabby lambda syntax. Sqeezed it into one statement for added unreadability.
(f=->n{n>1&&1+f[[n/2,3*n+1][n%2]]||0})[gets.to_i]
Some overhead because Ruby, unlike Python, is not happy about mixing numbers with booleans.
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
$>
Rebmu: 28
u[++jE1 AeEV?a[d2A][a1M3a]]j
On a problem this brief and mathy, GolfScript will likely win by some percent against Rebmu (if it's not required to say, read files from the internet or generate JPG files). Yet I think most would agree the logic of the Golfscript is nowhere near as easy to follow, and the total executable stack running it is bigger.
Although Rebol's own creator Carl Sassenrath told me he found Rebmu "unreadable", he is busy, and hasn't time to really practice the pig-latin-like transformation via unmushing. This really is merely transformed to:
u [
++ j
e1 a: e ev? a [
d2 a
] [
a1 m3 a
]
]
j
Note that the space was required to get an a: instead of an a. This is a "set-word!" and the evaluator notices that symbol type to trigger assignment.
If it were written in unabbreviated (yet awkwardly-written Rebol), you'd get:
until [
++ j
1 == a: either even? a [
divide a 2
] [
add 1 multiply 3 a
]
]
j
Rebol, like Ruby, evaluates blocks to their last value. The UNTIL loop is a curious form of loop that takes no loop condition, it just stops looping when its block evaluates to something not FALSE or NONE. So at the point that 1 == the result of assigning A (the argument to rebmu) to the result of the Collatz conditional (either is an IF-ELSE which evaluates to the branch it chooses)... the loop breaks.
J and K are initialized to integer value zero in Rebmu. And as aforementioned, the whole thing evaluates to the last value. So a J reference at the end of the program means you get the number of iterations.
Usage:
>> rebmu/args [u[++jE1 AeEV?a[d2A][a1M3a]]j] 16
== 4
dc, 27 characters
Applying boothby's black magic:
?[d3*1+d2%5*1+/d1<x]dsxxkzp
I'm not really sure if I understand how - or that - it works.
Usage:$ dc collatz.dc <<< 7
16
dc, 36 characters
My own creation; a somewhat more traditional approach, even tho I had to wrangle with the language a fair bit to overcome the lack of an else part to if statements:
?[2/2Q]se[dd2%[0=e3*1+]xd1<x]dsxxkzp
Internally it produces all numbers of the sequence and stores them on the stack, then pops the final 1 and displays the stack height.
Q,46
{i::0;{x>1}{i+:1;$[x mod 2;1+3*x;(_)x%2]}\x;i}
newLISP - 94 chars
Strangely similar to Valentin's Scheme answer... :) I'm let down here by verbosity of the language but there's a bitshift division which appears to work...
(let(f(fn(x)(cond((= x 1)0)((odd? x)(++(f(++(* 3 x)))))(1(++(f(>> x)))))))(f(int(read-line))))
As I usually do, I will start the answers off with my own.
JavaScript, 46 44 chars (run on console)
for(n=prompt(),c=1;n>1;n=n%2?n*3+1:n/2,++c)c
F# - 65 chars
let rec c n=function 1->n|i->c(n+1)(if i%2=0 then i/2 else i*3+1)
Java, 165, 156, 154,134,131,129,128,126 (verbose languages need some love too)
class a{public static void main(String[]a){for(int x=Short.valueOf(a[0]),y=0;x>1;x=x%2<1?x/2:x*3+1,System.out.println(++y));}}
All is done inside the for
for(int x=Short.valueOf(a[0]),y=0;x>1;x=x%2<1?x/2:x*3+1,System.out.println(++y))
That's freaking beautiful man. Thanks to Pater Taylor!!!, and the idea of using a for loop was stolen from ugoren
I replaced Integer for Short.
C, 70 69 chars
Quite simple, no tricks.
Reads input from stdin.
a;
main(b){
for(scanf("%d",&b);b-1;b=b%2?b*3+1:b/2)a++;
printf("%d",a);
}
J, 30 characters
<:#-:`(1+3&*)`]@.(2&|+1&=)^:a:
Turned out quite a bit longer than desired
usage:
<:#-:`(1+3&*)`]@.(2&|+1&=)^:a:2
1
<:#-:`(1+3&*)`]@.(2&|+1&=)^:a:16
4
<:#-:`(1+3&*)`]@.(2&|+1&=)^:a:5
5
<:#-:`(1+3&*)`]@.(2&|+1&=)^:a:7
16
<:#-:`(1+3&*)`]@.(2&|+1&=)^:a:27
111
-:`(1+3&*)`]is a gerund composed of three verbs, used on three occasions.-:means "halve",(1+3&*)or(1+3*])encodes the multiplication step and](identity) aids termination.2&|+1&=forms an index to the gerund. literally, "the remainder after division by two plus whether it equals one".#verb^:a:iterates the function until the result is stable (here, forced explicitly), while collecting the steps, then counts them. Stolen from @JB.<:decrements the step count by one to align with the question requirements.
APL (31)
A←0⋄A⊣{2⊤⍵:1+3×⍵⋄⍵÷2}⍣{⍺=A+←1}⎕


