g | x | w | all
Bytes Lang Time Link
046AWK250328T185718Zxrs
091SAKO250322T164921ZAcrimori
032YASEPL240507T161825Zmadeforl
017Pip230212T205038ZThe Thon
011Vyxal 3240504T044443ZDLosc
8867Scala 3240504T083939Z138 Aspe
076Acc!!240504T072147ZMukundan
016Pyt240503T224215ZKip the
011Nekomata230827T064918Zalephalp
012Thunno 2230812T172726ZThe Thon
015Pyt230212T142142ZKip the
012Vyxal230205T145628Zlesobrod
070Wolfram Language Mathematica230205T152306Zlesobrod
030JavaScript ES6181104T203427ZArnauld
5015Nim220815T034148ZQaziquza
025K ngn/k230131T104852Zzoomlogo
075Nibbles230131T101910Zxigoi
nan230128T175843ZThe Thon
035dc220811T230713ZBenji
075C gcc211214T003428ZBenji
056Factor + math.extras210327T020203Zchunes
061R181114T162016ZSumner18
074Gambit Scheme gsi181214T155849Zsporkl
049Dart181214T125359ZElcan
039x86 machine code181105T235539Zuser3604
012MathGolf181109T124226Zmaxb
018JAEL181104T211349ZEduardo
01405AB1E181105T090256ZKevin Cr
064Rust181104T205235ZEndenite
056Haskell181104T233128Zflawr
011Stax181105T175128Zwastl
062C# .NET Core181105T170950ZMeerkat
141Emojicode 0.5181105T163913ZX1M4L
044Python 2181104T212921ZQuintec
039Haskell181104T234325Zlynn
052PowerShell181105T100908ZJ. Bergm
075Racket181105T112202ZGalen Iv
070Red181105T092905ZGalen Iv
030Perl 6181104T232313ZJo King
046Retina 0.8.2181104T224545ZNeil
079Common Lisp181104T220009ZJRowan
035Wolfram Language Mathematica181104T214026ZMisha La
033Add++181104T204829Zcaird co
053Clean181104T211904ZΟurous
039perl Minteger nlE181104T211613Zuser7392
012Pyth181104T205349ZMr. Xcod
009Jelly181104T204100ZErik the

AWK, 46 bytes

{for(print$1;$1;)print$1=$1%2?($1-1)/2:$1*3+1}

Attempt This Online!

SAKO, 98 91 bytes

2)CZYTAJ:N
DRUKUJ(9,0):N
1)N=ENT((N×3+1)/6*MOD(N,2))
DRUKUJ(9,0):N
GDYN=0:2,INACZEJ1
KONIEC

This probably isn't the shortest solution due to the repeated DRUKUJ, but I have no idea how to make it shorter.

Reads from STDIN. For results above 10 digits long prints in E notation.

Old solution, 98 bytes

2)CZYTAJ:N
DRUKUJ(9,0):N
1)D=1-MOD(N,2)
N=(6*D×(D+N-1))/2+D
DRUKUJ(9,0):N
GDYN=0:2,INACZEJ1
KONIEC

Uses the formula N=(6*D×(D+N-1)+2×D)/2 where D = 1 - N mod 2 for calculating the next value in the sequence.

This is a kind of port of my solution for normal Collatz Conjecture here.

YASEPL, 32 bytes

=x'(+`1-<!z$x%]2!-/-/3`2!*3++[-<

explanation:

=x'(+`1-<!z$x%]2!-/-/3`2!*3++[-<     packed
=x'(+                                get user input (output number) and add it by one
     `1                 !   +[       while X+1 != 1
       -                               subtract 1 from X
        <                              print X out
         !z$x%]2                       if X % 2 == 1...
                !-/                      subtract 1 and divide by 2
                   -/3`2!*3+           else, multiply by 3 and add 1
                              -<     print last number when finished 

Pip, 29 17 bytes

W Paa:%a?HVaa*3+1

Attempt This Online!

-12 thanks to @DLosc

Explanation

W Paa:%a?HVaa*3+1  # Implicit input as a command line argument, `a`
W                  # Loop while the condition is truthy (!= 0)
  Pa               # Print `a` and use this as the condition:
    a:             #  Assign the following to `a`:
      %a?          #   If a is even then:
         HVa       #    a//2
            a*3+1  #   Otherwise, a*3+1

Vyxal 3, 11 bytes

э:ḃ[v½|Tꜝ}Ŀ

Try it Online!

Explanation

э:ḃ[v½|Tꜝ}Ŀ­⁡​‎‎⁡⁠⁡‏‏​⁡⁠⁡‌⁢​‎‎⁡⁠⁢‏‏​⁡⁠⁡‌⁣​‎‎⁡⁠⁣‏‏​⁡⁠⁡‌⁤​‎‎⁡⁠⁤‏⁠‎⁡⁠⁢⁣‏⁠‎⁡⁠⁣⁢‏‏​⁡⁠⁡‌⁢⁡​‎‎⁡⁠⁢⁡‏⁠‎⁡⁠⁢⁢‏‏​⁡⁠⁡‌⁢⁢​‎‎⁡⁠⁢⁤‏⁠‎⁡⁠⁣⁡‏‏​⁡⁠⁡‌⁢⁣​‎‎⁡⁠⁣⁣‏‏​⁡⁠⁡‌­
э            # ‎⁡Convert the next three elements to a lambda function:
 :           # ‎⁢ Duplicate
  ḃ          # ‎⁣ Parity (1 if odd, 0 if even)
   [  |  }   # ‎⁤ Ternary expression based on that value:
    v½       # ‎⁢⁡  If truthy (1/odd), decrement and halve
       Tꜝ    # ‎⁢⁢  If falsey (0/even), triple and increment
          Ŀ  # ‎⁢⁣Apply that function to the input until it repeats a value, and return
             # the list of unique values visited
💎

Created with the help of Luminespire.


Alternate 11 bytes, port of Mukundan314's Acc!! answer:

λ:Tꜝ6←ḃ*Ṡ}Ŀ

Try it online!

Scala 3, 88 67 bytes

Saved 21 bytes thanks to @Mukundan314


Golfed version. Attempt This Online!

def c(n:Int):List[Int]=if(n<1)List()else n::c(List(3*n+1,n/2)(n%2))

Ungolfed version. Attempt This Online!

object Main {
  def main(args: Array[String]): Unit = {
    List(1, 2, 3, 10, 14).map(collatz).foreach(println)
  }

  def collatz(n: Int): List[Int] = {
    if (n == 0) List()
    else n :: collatz(next(n))
  }

  def next(n: Int): Int = {
    if (n % 2 == 1) n / 2
    else 3 * n + 1
  }
}

Acc!!, 76 bytes

Count i while N {
i
}
Count i while _ {
Write 49)*(_
Write 9
(_*3+1)/6^(_%2)

Try it online!

Intput and Output are both in unary

Pyt, 16 bytes

`ĐĐ2%?ŕ⁻₂:ŕ3*⁺;ł

Try it online!

`                  do...
 ĐĐ                (implicit input if stack is empty) Đuplicate top of stack twice
   2%              modulo 2
     ?             is top of stack not 0? (Truthy)
      ŕ            if so, ŕemove the top of the stack
       ⁻           decrement
        ₂          divide by ₂
     :             else:
      ŕ            ŕemove the top of the stack
       3*          multiply by 3
         ⁺         increment
     ;             either way, continue from here
      ł          ... while top of stack is not 0 (Falsy); implicit print upon exit

Nekomata, 11 bytes

ᶦ{Z:←½$3*→I

Attempt This Online!

ᶦ{Z:←½$3*→I
ᶦ{              Iterate until failure:
  Z                 Check if nonzero
   :                Duplicate
    ←               Decrement
     ½              Halve; fails if odd
      $             Swap
       3*           Multiply by 3
         →          Increment
          I         Choose the first value that doesn't fail

Thunno 2, 12 bytes

(ß;DE?3×⁺:⁻½

Try it online!

Explanation

(ß;DE?3×⁺:⁻½  # implicit input
(             # while loop:
 ß            #   (condition)  print the number without popping
              #                and test if it's truthy (non-zero)
  ;D          #   (body)  duplicate the current integer
    E?        #           if it's even:
      3×      #             multiply it by 3
        ⁺     #             and then add one
         :    #           otherwise:
          ⁻   #             decrement it
           ½  #             and then halve it

Pyt, 15 bytes

`ĐĐ2%?ŕ₂:ŕ3*⁺;ł

Try it online!

`             ł        do... while top of stack is not 0; implicit print upon exiting loop
 ĐĐ                    duplicate top of stack twice (implicit input if empty)
   2%                  modulo 2
      ?ŕ₂              if top of stack is truthy, then pop from stack and divide next by 2 
        :ŕ3*⁺          else: pop from stack and multiply next term by 3 and add 1
             ;         end if-then-else statement

Vyxal, 15 12 bytes

Thanks to @Steffan i learned more about Vyxal!

{…:|:∷[2ḭ|T›

Try it Online!

Naive approach for beginners:

{…:Ṡ|:₂[3*›|‹2/

Wolfram Language (Mathematica), 70 bytes

NestWhileList[If[EvenQ@#,3#+1,(#-1)/2]&,#,Unequal,All,\[Infinity],-1]&

Try it online!

Longer than previous WL, but with cycles detection.

JavaScript (ES6), 30 bytes

f=n=>n&&n+[,f(n&1?n>>1:n*3+1)]

Try it online!

Nim, 65 50 bytes (-15 due to xigoi)

proc f(n:int)=
 echo n;if n>0:f [n*3+1,n/%2][n%%2]

Attempt This Online!

Simple recursive solution cum array-based due to xigoi.

K (ngn/k), 25 bytes

{x>0}{$[2!x;_x%2;1+3*x]}\

Try it online!

Nibbles, 7.5 bytes

`.$?`%$~@+*3@~

Attempt This Online!

`. Iterate while unique
$   starting at input
?   if
`%   modulo (also save the quotient)
$     the number
~     2
@    then the quotient
+    else add
*3    multiply by 3
@      the number
~     1

Thunno d, \$ 19 \log_{256}(96) \approx \$ 15.64 bytes

[zuZK!)2%?1-2,(3*1+

(No ATO link since this needs v1.2.2 and ATO is on v1.2.1)

Explanation

[zuZK!)2%?1-2,(3*1+  # Implicit input
[                    # Loop forever:
 zu                  #  Quadruplicate the value on the top of the stack
   ZK                #  Print with a trailing newline
     !)              #  If it's 0, break
       2%?           #  If it's odd:
          1-         #   Subtract one
            2,       #   And integer divide by two
              (      #  Else:
               3*    #   Multiply by three
                 1+  #   And add one
                     #  This value is on the top of the stack for the next iteration
                     # The d flag stops the implicit output at the end

Screenshot

Screenshot

dc, 35 bytes

[3*1+]0:s[1-2/]1:s[pd2%;sxd0<l]dslx

Try it online!

C (gcc), 75 bytes

#include<stdio.h>
int g(int x){printf("%d ",x);x?g(x=x%2?(x-1)/2:3*x+1):0;}

Try it online!

Factor + math.extras, 56 bytes

[ [ .s dup odd? [ 1 - 2/ ] [ 3 * 1 + ] if ] until-zero ]

Try it online!

Explanation:

R, 66 61 bytes

-5 bytes thanks to Robert S. in consolidating ifelse into if and removing brackets, and x!=0 to x>0

print(x<-scan());while(x>0)print(x<-`if`(x%%2,(x-1)/2,x*3+1))

instead of

print(x<-scan());while(x!=0){print(x<-ifelse(x%%2,(x-1)/2,x*3+1))}

Try it online!

Gambit Scheme (gsi), 74 bytes

(define(f n)(if(= 0 n)'()(cons n(f(if(even? n)(+ (* 3 n)1)(/(- n 1)2))))))

Try it online!

Dart, 49 bytes

f(n){for(;n>0;n=n%2>0?(n-1)>>1:(n*3)+1)print(n);}

Try it online!

x86 machine code, 39 bytes

00000000: 9150 6800 0000 00e8 fcff ffff 5958 a901  .Ph.........YX..
00000010: 0000 0074 04d1 e8eb 066a 035a f7e2 4009  ...t.....j.Z..@.
00000020: c075 dec3 2564 20                        .u..%d 

Assembly (NASM syntax):

section .text
	global func
	extern printf
func:					;the function uses fastcall conventions
	xchg eax, ecx			;load function arg into eax
	loop:
		push eax
		push fmt
		call printf	;print eax
		pop ecx
		pop eax
		test eax, 1	;if even zf=1
		jz even		;if eax is even jmp to even
		odd:		;eax=eax/2
			shr eax, 1
			jmp skip
		even:		;eax=eax*3+1
			push 3
			pop edx
			mul edx
			inc eax
		skip:
		or eax, eax
		jne loop	;if eax!=0, keep looping
	ret			;return eax
section .data
	fmt db '%d '

Try it online!

MathGolf, 12 bytes

{o_¥¿½É3*)}∟

Try it online!

Explanation

{             Start block of arbitrary length
 o            Output the number
  _           Duplicate
   ¥          Modulo 2
    ¿         If-else with the next two blocks. Implicit blocks consist of 1 operator
     ½        Halve the number to integer (effectively subtracting 1 before)
      É       Start block of 3 bytes
       3*)    Multiply by 3 and add 1
          }∟  End block and make it do-while-true

JAEL, 18 bytes

![ؼw>î?èÛ|õÀ

Try it online!

05AB1E, 15 14 bytes

[Ð=_#Èi3*>ë<2÷

-1 byte thanks to @MagicOctopusUrn.

Try it online.

Explanation:

[             # Start an infinite loop
 Ð            #  Duplicate the top value on the stack three times
              #  (Which will be the (implicit) input in the first iteration)
  =           #  Output it with trailing newline (without popping the value)
   _#         #  If it's exactly 0: stop the infinite loop
     Èi       #  If it's even:
       3*     #   Multiply by 3
         >    #   And add 1
      ë       #  Else:
       <      #   Subtract 1
        2÷    #   And integer-divide by 2

Rust, 65 64 bytes

|mut n|{while n>0{print!("{} ",n);n=if n&1>0{n>>1}else{n*3+1};}}

Try it online!

Haskell, 76 69 61 56 bytes

I feel like this is way too long. Here l produces an infinite list of the inverse-collatz sequence, and the anonymous function at the first line just cuts it off at the right place.

Thanks for -5 bytes @ØrjanJohansen!

fst.span(>0).l
l r=r:[last$3*k+1:[div k 2|odd k]|k<-l r]

Try it online!

Stax, 11 bytes

₧↑╔¶┘tÇ╣;↑è

Run and debug it

C# (.NET Core), 62 bytes

a=>{for(;a>0;a=a%2<1?a*3+1:a/2)Console.Write(a+" ");return a;}

Try it online!

Ungolfed:

a => {
    for(; a > 0;                // until a equals 0
        a = a % 2 < 1 ?             // set a depending on if a is odd or even
                a * 3 + 1 :             // even
                a / 2                   // odd (minus one unnecessary because of int casting)
    )
        Console.Write(a + " "); // writes the current a to the console
    return a;                   // writes a to the console (always 0)
}

Emojicode 0.5, 141 bytes

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

Try it online!

🐖🎅🏿🍇
🍮a🐕      👴 input integer variable 'a'
😀🔡a 10      👴 print input int
🔁▶️a 0🍇      👴 loop while number isn’t 0
🍊😛🚮a 2 1🍇     👴 if number is odd
🍮a➗a 2       👴 divide number by 2
🍉
🍓🍇      👴 else
🍮a➕✖️a 3 1   👴 multiply by 3 and add 1
🍉
😀🔡a 10     👴 print iteration
🍉🍉

Python 2, 54 52 44 bytes

n=input()
while n:print n;n=(n*3+1,n/2)[n%2]

-2 bytes thanks to Mr. Xcoder

There must certainly be a faster way. Oddly, when I tried a lambda it was the same bytecount. I'm probably hallucinating.

Try it online!

Haskell, 40 39 bytes

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

Try it online!

Now without the final 0.

PowerShell, 53 52 bytes

param($i)for(;$i){$i;$i=(($i*3+1),($i-shr1))[$i%2]}0

Try it Online!

Edit:
-1 byte thanks to @mazzy

Racket, 75 bytes

(define(f n)(cons n(if(= n 0)'()(if(odd? n)(f(/(- n 1)2))(f(+(* 3 n)1))))))

Try it online!

Equivalent to JRowan's Common Lisp solution.

Red, 70 bytes

func[n][print n if n = 0[exit]either odd? n[f n - 1 / 2][f n * 3 + 1]]

Try it online!

Perl 6, 30 bytes

{$_,{$_%2??$_+>1!!$_*3+1}...0}

Try it online!

Anonymous code block that returns a sequence.

Explanation:

{$_,{$_%2??$_+>1!!$_*3+1}...0}
{                            }   # Anonymous code block
   ,                     ...     # Define a sequence
 $_                              # That starts with the given value
    {                   }        # With each element being
     $_%2??     !!               # Is the previous element odd?
           $_+>1                 # Return the previous element bitshifted right by 1
                  $_*3+1         # Else the previous element multiplied by 3 plus 1
                            0    # Until the element is 0

Retina 0.8.2, 46 bytes

.+
$*
{*M`1
^(..)+$
$&$&$&$&$&$&111
1(.*)\1
$1

Try it online! Explanation:

.+
$*

Convert to unary.

{

Repeat until the value stops changing.

*M`1

Print the value in decimal.

^(..)+$
$&$&$&$&$&$&111

If it is even, multiply by 6 and add 3.

1(.*)\1
$1

Subtract 1 and divide by 2.

The trailing newline can be suppressed by adding a ; before the {.

Common Lisp, 79 bytes

(defun x(n)(cons n(if(= n 0)nil(if(=(mod n 2)0)(x(+(* n 3)1))(x(/(- n 1)2))))))

Try it online!

Wolfram Language (Mathematica), 35 bytes

0<Echo@#&&#0[3#+1-(5#+3)/2#~Mod~2]&

Try it online!

0<Echo@# && ...& is short-circuit evaluation: it prints the input #, checks if it's positive, and if so, evaluates .... In this case, ... is #0[3#+1-(5#+3)/2#~Mod~2]; since #0 (the zeroth slot) is the function itself, this is a recursive call on 3#+1-(5#+3)/2#~Mod~2, which simplifies to 3#+1 when # is even, and (#-1)/2 when # is odd.

Add++, 38 35 33 bytes

D,f,@:,d3*1+$2/iA2%D
+?
O
Wx,$f>x

Try it online!

How it works

First, we begin by defining a function \$f(x)\$, that takes a single argument, performs the inverted Collatz operation on \$x\$ then outputs the result. That is,

$$f(x) = \begin{cases} x \: \text{is even}, & 3x+1 \\ x \: \text{is odd}, & \lfloor\frac{x}{2}\rfloor \end{cases}$$

When in function mode, Add++ uses a stack memory model, otherwise variables are used. When calculating \$f(x)\$, the stack initially looks like \$S = [x]\$.

We then duplicate this value (d), to yield \$S = [x, x]\$. We then yield the first possible option, \$3x + 1\$ (3*1+), swap the top two values, then calculate \$\lfloor\frac{x}{2}\rfloor\$, leaving \$S = [3x+1, \lfloor\frac{x}{2}\rfloor]\$.

Next, we push \$x\$ to \$S\$, and calculate the bit of \$x\$ i.e. \$x \: \% \: 2\$, where \$a \: \% \: b\$ denotes the remainder when dividing \$a\$ by \$b\$. This leaves us with \$S = [3x+1, \lfloor\frac{x}{2}\rfloor, (x \: \% \: 2)]\$. Finally, we use D to select the element at the index specified by \$(x \: \% \: 2)\$. If that's \$0\$, we return the first element i.e. \$3x+1\$, otherwise we return the second element, \$\lfloor\frac{x}{2}\rfloor\$.

That completes the definition of \$f(x)\$, however, we haven't yet put it into practice. The next three lines have switched from function mode into vanilla mode, where we operate on variables. To be more precise, in this program, we only operate on one variable, the active variable, represented by the letter x. However, x can be omitted from commands where it is obviously the other argument.

For example, +? is identical to x+?, and assigns the input to x, but as x is the active variable, it can be omitted. Next, we output x, then entire the while loop, which loops for as long as \$x \neq 0\$. The loop is very simple, consisting of a single statement: $f>x. All this does is run \$f(x)\$, then assign that to x, updating x on each iteration of the loop.

Clean, 53 bytes

import StdEnv
$0=[0]
$n=[n: $if(isOdd n)(n/2)(n*3+1)]

Try it online!

perl -Minteger -nlE, 39 bytes

{say;$_=$_%2?$_/2:3*$_+1 and redo}say 0

Pyth, 12 bytes

.u?%N2/N2h*3

Try it here as a test suite!

Jelly, 9 bytes

:++‘ƊḂ?Ƭ2

Try it online!