g | x | w | all
Bytes Lang Time Link
269Bespoke250827T075215ZJosiah W
055C# 10250321T152545Zjuanferr
014Vyxal 3250226T091817ZWeird Gl
050Raku Perl 6 rakudo250321T160219Zxrs
083SAKO250321T123323ZAcrimori
880ArnoldC250304T111503ZThemooni
040Swift 6250302T020937ZmacOSist
038AWK250227T172106Zxrs
021Jalapeño250212T042321ZATaco
073Periodically250207T193033Zmadeforl
068ibe241121T201528Zmadeforl
053TI84 BASIC240509T150353Zmadeforl
070Acc!!171128T092436ZDLosc
023Uiua240315T221403ZZylviij
405Punchtape240311T192451Zmadeforl
010Nekomata230604T023859Zalephalp
031><> Fish230604T013313Zchunes
017Thunno 2230603T181516ZThe Thon
011Vyxal220410T011007ZnaffetS
052Python 2130801T181403ZValentin
040Gambit scheme130801T172344ZValentin
nanFig221003T202818ZSeggan
071brev220821T195046ZSandra
011Husk220821T022522ZDLosc
023Pyth 23byte220821T015313Zbigbean
019Pip200830T222312ZDLosc
037Knight220820T215259Z97.100.9
012Jelly160418T065245ZDennis
026Alice170414T220109ZMartin E
054Haskell220510T130442ZEd The &
022Factor + projecteuler.014220508T201903Zchunes
021ngn/k220324T005057Zulucs
037C gcc220408T063122ZQaziquza
060Ruby220410T035105Zoeuf
063Desmos220410T030840ZAiden Ch
217LOLCODE220410T011924ZnaffetS
085rusty_deque220409T222813Zbigyihsu
067Rust220324T040232ZSapherey
038Haskell220323T160040Zmatteo_c
029Julia 1.0220217T214148ZMarcMush
027Julia 0.6160418T175023ZDennis
054Julia220215T021942ZDavid Sc
015x86 machine code220215T014757ZEasyasPi
067tinylisp171026T214357ZDLosc
nan220123T202946Zserdar e
028Racket211213T225910Zgantz gi
015HBL211207T185249ZDLosc
064Python 3211207T182459ZAlan Bag
026Burlesque211122T175651ZDeathInc
028><>160414T095649ZAaron
090BitCycle u201011T035450ZDLosc
101Python210315T205607Zuser1008
075Lua210301T142856ZJ. А. de
062Rust210228T000809Zsmitop
071Forth gforth201110T095837ZRazetime
047Haskell200831T034151Zbigyihsu
036MAWP200826T092651ZRazetime
845FRACTRAN200420T044447ZAnders K
063Kotlin200322T055618Zsnail_
024FRACTRAN200321T205737ZAviFS
023Keg rR191212T124105Zuser8505
068Wren191212T125923Zuser8505
054SmileBASIC170201T235000Z12Me21
033Aceto170512T103223ZL3viatha
01505AB1E190117T192310ZWisław
072Ruby190128T044534ZCG One H
015Japt180221T151409ZShaggy
035JavaScript190123T220537ZOliver
023><>160505T113612ZSok
024Pushy181224T214336ZFlipTack
4333C gcc170404T232446ZBijan
007MathGolf180913T140101Zmaxb
010Jelly181112T235315ZBubbler
048Python 2180913T162842ZTriggern
038Ahead180716T100339Zsnail_
043Julia 0.6180616T154933ZSundar R
073PHP180326T132317ZFrancisc
048Ruby180614T173503ZJoey
016MATL180512T211213ZStewie G
065Octave180512T202906ZStewie G
157Emojicode180509T165222ZX1M4L
054Java OpenJDK 8180326T124321ZX1M4L
028dc180509T142903ZToby Spe
044Hexagony180327T105510ZJo King
035Ruby180509T055929ZG B
050Add++180411T214503Zcaird co
029Befunge93180408T094021ZJo King
056brainfuck171227T142611ZJo King
016Brachylog180302T131701ZMartin E
096SNOBOL4 CSNOBOL4180221T160943ZGiuseppe
nanStax180221T154437ZWeijun Z
022Wumpus180221T141104ZMartin E
082Clean180109T200729ZΟurous
037Python 2160601T032342ZDennis
061Emacs/Common Lisp180109T034525Zuser8420
011Attache180109T051858ZConor O&
040Perl 6140406T192932ZMouq
033QBIC161205T173227Zsteenber
072CasioBasic170512T090011Znumberma
038PARI/GP170921T041027ZMD XF
139Emojicode170730T120948Zbetseg
076S.I.L.O.S170513T125436ZRohan Jh
038C170422T160913Z2501
060Game Maker Language131130T144508ZTimtech
067TCL 8.5131109T200215Zuser7795
047TIBasic170405T123735Zpizzapan
01680386 assembly170210T010457ZFUZxxl
048Python repl130802T222254Zboothby
053Java 8170127T112441ZLinnea G
060Clojure170118T201026ZCarcigen
053Java OpenJDK170107T035110ZPavel
077Clojure161206T050002Zclismiqu
071C#161214T120522ZAlfie Go
054Python 2150122T151012Zuser344
043Haskell150123T001654Znimi
055R161205T101433ZJAD
037Befunge 93161205T185049ZMercyBea
074Axiom161205T094506Zuser5898
040Befunge160414T073614ZSE - sto
036Mathcad160418T115534ZStuart B
122Oracle SQL 11.2160418T095948ZJeto
035Mathematica130802T162539Zmiles
024K150315T231020ZJohnE
034Perl 34 +1 chars130801T120459Zprimo
022Pyth150529T083145Zgcq
043Retina150529T033102Zrandomra
059This Programming Language150315T012556ZBobTheAw
026Fish 33 chars including whitespace140510T070723ZTalkTake
7373Haskell 73 Bytes 73 Chars140406T224258ZChristop
029JavaScript ES6 29 Characters140406T214551ZMT0
053~~! No Comment140404T150459Zcjfaure
nan140404T165850Zɐɔıʇǝɥʇu
136Java131130T193941ZAndrew G
061PowerShell131112T044735ZIszi
048C++130829T001602ZJoe Z.
049Ruby 1.9130901T133013Zdaniero
047C130830T151835ZFors
028Rebmu130814T043216ZHostileF
027dc130806T035048Zdaniero
046Q130801T141254Ztmartin
094newLISP130802T121918Zcormulli
018GolfScript130801T115134ZVolatili
nanAs I usually do130801T112246ZDoorknob
065F#130801T194221ZDaniel
126Java130801T154202Zjsedano
069C130801T163851Zugoren
030J130801T142908ZJohn Dvo
031APL130801T122237Zmarinus
023GolfScript130801T120813ZPeter 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);}}

Try it Online!

Vyxal 3, 19 15 14 bytes

{D¥$‹|›£e[½|T›

Vyxal It Online!

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}

Attempt This Online!

->$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 N=(6*D×N)/2+D 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

Try it online!

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

Attempt This Online!

{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                                  

Try it Online!

All test cases!

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])

ibe, 68 bytes

adadaddsQakqafEmwskWafWmQsjWmesdWmqmwahQmrafQmwalqakwajQmeshQmwmqasE

explanation soon

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

Attempt This Online!

ˡ{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

><> (Fish), 31 bytes

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

Try it

Thunno 2, 17 bytes

(1Q;Dɗ?3×⁺:½;ẋ)x⁻

Attempt This Online!

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

Vyxal, 17 12 11 bytes

∷[T›|½)İ2ḟ⇧

Try it Online!

-5 bytes thanks to lyxal

Removed flag thanks to emanresu A.

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

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

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

Try it online!

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!

Knight, 37 bytes

;=n+0P;=iT;W-1=nI%n 2+1*3n/n 2=i+1iOi

Try it online!

Jelly, 12 bytes

×3‘$HḂ?ß0’?‘

Try it online!

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$

Try it online!

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)

Factor + project-euler.014, 22 bytes

[ collatz length 1 - ]

Try it online!

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.

Attempt This Online!

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

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

Try it online!

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};

Try it online!

Nice way of practicing rust

Haskell, 39 38 bytes

saved 1 byte thanks to DLosc

f 2=1
f n=1+f(cycle[div n 2,n*3+1]!!n)

Attempt This Online!

Julia 1.0, 29 bytes

!n=n>1&&1+![n÷2,3n+1][n%2+1]

Try it online!

Based on Dennis' answer

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.

Try it online!

Julia, 54 chars

f(n,i)=n==1 ? i : n%2==0 ? f(n/2,i+=1) : f(n*3+1,i+=1)

Try it online!

Julia, 45 chars

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

Try it online!

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

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.

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
?(-.)(-+?().

Try it!

Explanation

Helper function:

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

Main function:

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

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

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

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!

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

><>, 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.

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

Try it online!

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- ;

Try it online!

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 ;

Try it online!

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.

Try it!

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.

Try it online!

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\$.

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!

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

Try it online!

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.

Original CollatzGameCleaned-up CollatzGame

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:

Keg -rR, 23 bytes (SBCS)

I really need to remember those new instructions.

0&{:1>|:2%[3*⑨|½]⑹

Try it online!

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
}

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÷}¼Ð#]¾

Try it online!

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

Japt, 18 15 bytes

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

Try it

JavaScript, 35 bytes

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

Try it online!

><>, 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=?

Pushy, 24 bytes

Zvt$h2C3*h}2/}2%zFhFt;F#

Try it online!

C (gcc), 43 33 bytes

f(x){x=~-x?f(x&1?3*x+1:x/2)+1:0;}

Try it online!

MathGolf, 7 bytes

kÅ■┐▲î 

Don't get fooled, there's a non-breaking space at the end of the program.

Try it online!

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.

Try it online!

Jelly, 10 bytes

×3‘ƊHḂ?Ƭi2

Try it online!

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)

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(...)

Ahead, 38 bytes

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

Try it online!

Julia 0.6, 43 bytes

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

Try it online!

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@

Try it online!

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'

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.

Emojicode, 157 bytes

🐖🎅🏿➡️🔡🍇🍮a🐕🍮c 0🔁▶️a 1🍇🍊😛🚮a 2 0🍇🍮a➗a 2🍉🍓🍇🍮a➕✖️a 3 1🍉🍮c➕c 1🍉🍎🔡c 10🍉

Try it online!

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;}

Try it online!

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'%<>./>=

Try it online!

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]}

Try it online!

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

Try it online!

-5 bytes thanks to rubber duck golfing!

How it works

D,f,@,		; Define a function 'f' that takes one argument
		; Example argument:	[10]
	dd	; Triplicate;	STACK = [10 10 10]
	2/i	; Halve;	STACK = [10 10 5]
	@	; Reverse;	STACK = [5 10 10]
	3*1+	; (n*3)+1;	STACK = [5 10 31]
	$	; Swap;		STACK = [5 31 10]
	2%	; Parity;	STACK = [5 31 0]
	D	; Select;	STACK = [5]

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

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

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

Befunge-93, 29 bytes

&<\+1\/2+*%2:+2*5:_$#-.#1@#:$

Try it online!

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|{/₂ℕ|×₃+₁}↰+₁

Try it online!

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∧

Try it online!

;.          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	

Try it online!

Stax, 12 bytesCP437

ÄFl,rBoU¡£&╦

14 bytes when unpacked,

1{h_3*^\_@gt%v

Run and debug online!

Adaptation of https://github.com/tomtheisen/stax/blob/master/testspecs/golf/CollatzTest.staxtest .

Wumpus, 22 bytes

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

Try it online!

Explanation

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

I   Read a decimal integer N from STDIN. At EOF (i.e. on subsequent 
    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))

Try it online!

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.

Try it online!

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))))))

Attache, 11 bytes

CollatzSize

Try it online!

Not much to say...

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)

Try it online!

Equivalent to this readable C code:

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

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

Emojicode, 139 bytes

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

Try it online!

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

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

Try it online!

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

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))))))

Java (OpenJDK), 53 bytes

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

Try it online!

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

Try it Online!

&>: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"

enter image description here

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

online

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-host to 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:

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))))

GolfScript, 24 23 21 20 18 chars

~{(}{3*).2%6\?/}/,

Assumes input on stdin. Online test

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

APL (31)

A←0⋄A⊣{2⊤⍵:1+3×⍵⋄⍵÷2}⍣{⍺=A+←1}⎕

GolfScript (23 chars)

~{.1&{.3*)}*.2/.(}do;],

Online test