title: Find your dog's age

text:
# Question
Title: Find your dog's age
# Task

Take the (integer) number of human years that the dog has lived, \\$n\\$, as input and return its age in dog years, \\$d\\$, to two decimal places.
The number of human years, \\$n\\$, will be between \\$1\\$ and \\$122\\$ inclusive: \\$n \in \[1,122\], n \in \Bbb{N}\\$.

According to BBC's Science Focus Magazine, the correct function for determining your dog's age is: $$ n = 16 \times \ln(d) + 31 $$ Where

*\\$n\\$ is the age in human years*

*\\$d\\$ is the age in dog years*

# Rules

The final output in dog years must be a decimal, **rounded to 2 decimal places.**

# Answer
> 2 votes
# Orst, 9 bytes

```
31FᎽGć2Š

```

Try it online!

As bytes, this is

```
F3 F1 1B FF 30 1C 64 F2 42

```

Or, encoded as UTF-8,

```
óñÿ0dòB
```

which can be run by omitting the `-u` flag (filled by default on TIO). Note the not shown `0x1b` and `0x1c` bytes

## How it works

```
31FᎽGć2Š - Full program. n is pushed to the stack
31       - Push 31
  F      - Subtract; n-31
   Ꮍ     - Push 16
    G    - Divide; (n-31)÷16
     ć   - Exp; exp((n-31)÷16)
      2Š - Round to 2 decimal places

```

# Answer
> 5 votes
# Io, 114 bytes

While you all are enjoying rounding built-ins in your language, Io doesn't have any of those convenient rounding built-ins...

```
method(x,I :=((((x-31)/16)exp*100)round asString);I=if(I size<3,"0","").. I;I asMutable atInsertSeq(I size-2,"."))

```

Try it online!

# Answer
> 4 votes
# Perl 5, ~~36~~ 31 bytes

```
printf"%.2f",1.0644944**($_-31)

```

Try it online!

Command line one-liner examples:

```
echo 52 | perl -ne 'printf"%.2f\n",2.71828**(($_-31)/16)'
echo 52 | perl -ne 'printf"%.2f\n",1.06449445**($_-31)'
echo 52 | perl -ne 'printf"%.2f",1.06449445**($_-31)'
echo 52 | perl -ne 'printf"%.2f",1.0644944**($_-31)'

for a in {1..122};do echo "Man: $a Dog: "`echo $a|perl -ne'printf"%.2f\n",1.0644944**($_-31)'`;done

```

# Answer
> 3 votes
# Jelly, 10 bytes

```
_31÷⁴Æeær2

```

A monadic Link accepting a float which yields a float. (As a full program a decimal input causes the result to be printed.)

**Try it online!**

### How?

```
_31÷⁴Æeær2 - Link: float, n
 31        - 31
_          - subtract         -> n-31
    ⁴      - 16
   ÷       - divide           -> (n-31)/16
     Æe    - exp(x)           -> exp((n-31)/16)
         2 - 2
       ær  - round to 10^(-y) -> round(exp((n-31)/16), 2)

```

# Answer
> 3 votes
# Integral, ~~14~~ 11 Bytes

My first Integral answer!

```
x▼◄w‼5*↕u*‼

```

Try it!

An alternative: `▲w‼!◄5*↕u*‼` (11 bytes)

## Explanation

```
x              Push 32
 ▼             x-1
  ◄            Subtraction
   w           Push 16
    ‼          Divide
     5         e ^ a
      *        100
       ↕       Multiplicaiton
        u      Round to the closest integer
         *     100
          ‼    Division

```

# Answer
> 2 votes
# APL+WIN, 13 bytes

Prompts for input of n:

```
⍎2⍕*(⎕-31)÷16

```

Try it online! Courtesy of Dyalog Classic

# Answer
> 2 votes
# Vyxal `s`, 23 bytes

```
31-16/W∆ehS\.€ḣh2wi\.$W

```

Try it Online!

From this answer two stupid features of Vyxal:

* Why \\$ln(x)^{-1}\\$ needs to take a list instead of digit?
* Seriously it cannot round a digit to n decimal places, so that part is handrolled.

# Answer
> 1 votes
# JavaScript (V8), ~~33~~ 32 bytes

```
a=>Math.exp(-~a/16-2).toFixed(2)

```

Try it online!

***Thanks to @my pronoun is monicareinstate for -1 byte***

# Answer
> 1 votes
# C (gcc), ~~35~~ ~~44~~ ~~38~~ 36 bytes

Saved a byte thanks to my pronoun is monicareinstate!!!
Saved 2 bytes thanks to Arnauld!!!
Added 10 bytes to fix a bug kindly pointed out by Kjetil S.

```
f(n){printf("%.2f",exp(-~n/16.-2));}

```

Try it online!

# Answer
> 1 votes
# Python 3, ~~52~~ ~~36~~ 35 bytes

Saved a whopping ~~16~~ 17 bytes thanks to Jonathan Allan!!!

```
lambda n:round(1.0644944**(n-31),2)

```

Try it online!

# Answer
> 1 votes
# cQuents, 24 bytes

```
:b$)/100
:R100*x_+$/16-2

```

Try it online!

For some reason, rounding works on the whole line. I would do `/100/R100*`, but floats went all `9`y on me.

# Answer
> 1 votes
# , 28 bytes

```
round(exp((scan()-31)/16),2)

```

Try it online!

There seems to be some controversy about whether trailing zeros must be printed. If so, the following 35 byte solution works:

```
sprintf("%.2f",exp((scan()-31)/16))

```

# Answer
> 1 votes
# bc, 40 bytes

```
scale=2
define f(n){return e((n-31)/16)}

```

Try it online!

# Answer
> 1 votes
# Japt, <sup>~~12~~</sup> 11 bytes

-1 byte thanks to @Shaggy

```
Me°U/G-2 x2

```

Try it

## Explanation

```
Me°U/G-2 x2
Me            //  exp(
  °U          //      (U + 1)
    /G-2      //              / 16 - 2
              //  )
          x2  //  round to 2 decimal digits

```

# Answer
> 1 votes
# Charcoal, 20 bytes

```
﹪%.2fＸ¹·⁰⁶⁴⁴⁹⁴⁴⁵⁻Ｎ³¹

```

Try it online! Link is to verbose version of code. Numeric constant stolen from @JonathanAllan. Explanation:

```
                Ｎ      Input as a number
               ⁻ ³¹    Subtract literal 31
     Ｘ¹·⁰⁶⁴⁴⁹⁴⁴⁵        Raise literal 1.06449445 to that power
﹪%.2f                   Format using literal format string `%.2f`
                        Implicitly print

```

# Answer
> 1 votes
# MathGolf, 19 bytes

```
T-☻/e▬♪*i♂‼/%5≥+♀∩*

```

If only MathGolf had a round builtin.. :/
6 bytes are used for the actual formula, 13 for rounding to 2 decimals, haha.

I/O both as a float.

Try it online.

**Explanation:**

```
T-            # Subtract 31 from the (implicit) input-float
              #  i.e. 50.0 → 19.0
  ☻/          # Divide it by 16
              #  → 1.1875
    e▬        # Push 2.718281828459045 to the power this value
              #  → 3.2788737679386735
♪*            # Multiply it by 1000
              #  → 3278.8737679386735
  i           # Convert it to an integer, truncating the decimal values
              #  → 3278
   ♂          # Push 10
    ‼         # Apply the following two commands separated to the stack:
     /        #  Integer-division
      %       #  Modulo
              #   → 327 and 8
       5≥     # Check if the modulo-10 result (the last digit) is >= 5
              # (1 if truthy; 0 if falsey)
              #   → 327 and 1
         +    # Add that to the division-by-10 result
              #   → 328
          ♀∩  # Push 1/100
            * # Multiply that to the integer
              #   → 3.28
              # (note: `♀/` cannot be used, because it would act as integer division)
              # (after which the entire stack is output implicitly as result)

```

# Answer
> 1 votes
# Rust, 38 bytes

```
|n|print!("{:.2}",((n-31.)/16.).exp())

```

Try it online

# Answer
> 1 votes
# Zsh, 50 bytes

```
zmodload zsh/mathfunc
printf %.2f $[16*log($1)+31]

```

Try it Online!

Gives "dog years" per the **original** refs and examples. For example, the "ScienceFocus" article gives 2 examples, and the "Cell Systems" paper gives 1 example, as tabulated:
<sub> **`dog age | equivalent human age`**
**`actual years | approx. "dog years"`**
`1 | ~30`
`4 | ~52`
`12 | ~70`
</sub>

Do programmers ever read requirements?

# Answer
> 1 votes
# 05AB1E, 12 bytes

```
>16/Ížrsm2.ò

```

Try it online!

```
>16/Ížrsm2.ò  # full program
          .ò  # round...
     žr       # 2.718281828459045...
       sm     # to the power of...
              # implicit input...
>             # plus 1...
   /          # divided by...
 16           # literal...
    Í         # minus 2...
          .ò  # to...
         2    # literal...
          .ò  # decimal places
              # implicit output

```

# Answer
> 0 votes
## HP‑41C series, 18 B

You must place \\$n\\$ on top of the stack first (a. k. a. the `X` register). Then you can `XEQ` (execute) the following program:

```
01♦LBL "Y"         5 Bytes    global label requires 4 + (length of string) Bytes
   NULL            1 Byte     invisible Null byte before numbers
02 31              2 Bytes    X ≔ 31;  Y ≔
03 −               1 Byte     X ≔  − 31
   NULL            1 Byte     invisible Null byte before numbers
04 16              2 Bytes    place the value 16 on top of the stack; X ≔ 16
05 ∕               1 Byte     X ≔ ( − 31) ∕ 16
06 E↑X             1 Byte      raised to the power of X
07 FIX 2           2 Bytes    show (up to) two place after the radix point
08 RND             1 Byte     round the value
09 RTN             1 Byte     `RTN` does not affect local label search

```

The fixed decimal point display is always rounded. However, the display settings do not affect the internally stored numbers. To ensure all digits *after* the second decimal place are zero, too, `RND` (round) is applied.

---
Tags: code-golf, math, arithmetic
---


title: Box blur the string

text:
# Question
Title: Box blur the string
Box blur is a simple operation for blurring images. To apply box blur, simply replace each pixel with the average of its and the surrounding 8 pixels' values. Consider, for example, the following example, in which each "pixel" has a one-digit value:

\begin{array} {|r|r|}\hline 1 & 1 & 1 \\ \hline 1 & 7 & 1 \\ \hline 1 & 1 & 1 \\ \hline \end{array}

To get the blurred value of the center pixel we add its value to the 8 surrounding pixels' values and divide by 9.

$$ \frac{7+1+1+1+1+1+1+1+1}{9}=\frac{5}{3}=1.\overline{6} $$

Repeat this operation for every pixel and you've blurred the image.

## The task

Like pixels, strings are just numbers, so we can box blur them too. Your task is to take a string, which may have multiple lines, in some convenient format and return a new string that's been "blurred" by the above process. That is to say, you'll take each character's ASCII value and treat it as that character's value, "blur" the values, and return the new values' corresponding characters.

For example, given the following input:

```
'''#
''#'
'#''
#'''

```

Your output would look like this:

```
''&%
'&&&
&&&'
%&''

```

## Edges and corners

How do you blur a "pixel" that doesn't have eight neighbors because it's on an edge or in a corner of the "canvas"? For our purposes, you'll solve this by "filling in" the missing pixels with the nearest pixel's value. In the example below the missing value northwest of 1 is filled in with 1; likewise the missing value east of 6 is filled in with 6.

\begin{array} {|r|r|}\hline \color{silver}{1} & \color{silver}{1} & \color{silver}{2} & \color{silver}{3} & \color{silver}{3} \\ \hline \color{silver}{1} & 1 & 2 & 3 & \color{silver}{3} \\ \hline \color{silver}{4} & 4 & 5 & 6 & \color{silver}{6} \\ \hline \color{silver}{7} & 7 & 8 & 9 & \color{silver}{9} \\ \hline \color{silver}{7} & \color{silver}{7} & \color{silver}{8} & \color{silver}{9} & \color{silver}{9} \\ \hline \end{array}

## Rounding

For our purposes, you'll round fractions to the nearest integer. Halves should be rounded up.

## Rules

* The input will consist of one or more lines of one or more printable ASCII characters, i.e. `0x20``0x7E` inclusive, plus newlines if applicable to your input format. The string will be "rectangular," i.e. every line will have the same length.
* The input format is flexible, e.g. a single string with lines separated by newlines, an array of strings with one string per line, a multi-dimensional array of characters, etc.
* The output will be in the same format as the input, and likewise flexible.
* Standard rules and default I/O rules apply and standard loopholes are forbidden.
* This is so shortest solution in bytes wins.

## More examples

```
Input      Output

111        222
171        222
111        222

XXXXX      INNNI
,,X,,      ;DDD;
,,X,,      ,;;;,
,,X,,      ;DDD;
XXXXX      INNNI

'888'      /020/
8'''8      00/00
8'8'8      2/)/2
8'''8      00/00
'888'      /020/

103050709  111324256

!~         JU
~!         UJ

Q          Q

+--+       <22<
|  |       <22<
+--+       <22<

^          M
*          ;
*          ;
^          M

```

# Answer
# Vyxal, 20 bytes

```
4(∩ṘǏǔ)3vl3lƛ∩ṠCvṁṙC

```

Try it Online!

A mess. Input as a list of rows, output as a char matrix.

```
4(    )              # Four times...
  ∩Ṙ                 # Rotate 90°
    Ǐǔ               # Prepend the first item
       3vl           # Cut each into chunks of length 3
          3l         # Cut into chunks of length 3
            ƛ        # Over each list of lists of chunks...
             ∩       # Transpose into a list of 3x3 chunks
              Ṡ      # Stringify each chunk
               C     # Take the charcodes
                vṁṙ  # Take the mean of each and round back to integers
                   C # Convert back to characters

```
> 5 votes

# Answer
# , 47 45 bytes

```
(0.5<.@+9%~3+/\"#.3+/\(|.@|:@,{:)^:4)&.(3&u:)

```

Try it online!

*-2 thanks to ovs*

* `&.(3&u:)` Do everything that follows "under" converting to ascii code. This means it gets converted back automatically at the end.
* `({.|.@|:@,])^:4)` Standard reverse/transpose trick to fill out the sides and top.
* `3+/\"#.3+/\` Even though J has a built-in for applying a verb to "tiles" -- in this case it's 1 byte shorter to scan sum rows in groups of 3, then scan sum colums in groups of 3 to get the 3x3 tile averages.
* `9%~` Divide each by 9 for the average.
* `0.5<.@+` And round.
> 4 votes

# Answer
# Octave with Image Package, 50 bytes

```
@(X)char(round(imfilter(+X,~~e(3)/9,'replicate')))

```

Try it online!
> 4 votes

# Answer
# Jelly, 20 bytes

```
1ịṭṚZµ4¡O+3\Z$⁺+4:9Ọ

```

A monadic Link that accepts a list of lines and yields a list of lines.

**Try it online!** Or see the test-suite.

### How?

```
1ịṭṚZµ4¡O+3\Z$⁺+4:9Ọ - Link: list of lines, T
     µ4¡             - repeat four times (starting with T):
1                    -   one
 ị                   -   index into -> top row
   Ṛ                 -   reverse (the current lines)
  ṭ                  -   tack -> reversed current lines + top row
    Z                -   transpose
        O            - convert to ordinals
              ⁺      - do this twice:
             $       -   last two links as a monad:
          3\         -     three-part reduce  with:
         +           -       addition
            Z        -     transpose
               +4    - add four
                 :9  - integer divide by nine
                   Ọ - convert to characters

```
> 2 votes

# Answer
# Pyth, 44 bytes

```
L++hbbebDONRmsM.:d3CN;jmsmC+.5ck9dOOCMMyyM.z

```

Try it online!

Takes each line of the string as a separate input.

### Explanation

```
L++hbbeb                                        define y(b) as the "filling in" for the edges
        DONRmsM.:d3CN;                          define O(N) to transpose then blur the rows of a list by splitting into sublists of length 3 and mapping to their sum
                                          .z    put all available inputs into a list
                                       yyM      apply y to the rows and columns
                                    CMM         convert strings to lists of codepoints
                                  OO            apply the blurring, the two transpositions mean it ends as it started
                       m         d              map to
                        sm                      the joined strings of the map of
                          C                     the ascii value of the floor of
                           +.5ck9               0.5 + each element divided by 9
                      j                         join on newlines

```
> 2 votes

# Answer
# Uiua SBCS, 30 bytes

```
≡≡⍜(-@\0|⁅÷9/+♭)◫3_3⍥(≡⇌⍉⊂⊢.)4

```

Try it!

```
≡≡⍜(-@\0|⁅÷9/+♭)◫3_3⍥(≡⇌⍉⊂⊢.)4
                    ⍥(      )4  # repeat four times
                         ⊂⊢.    # prepend first row of array to array
                      ≡⇌⍉       # rotate
                ◫3_3            # 3x3 windows
≡≡                              # map over each window
  ⍜(-@\0|      )                # operate on code points, leaving string intact
              ♭                 # flatten
            /+                  # sum
          ÷9                    # divide by 9
         ⁅                      # round

```
> 2 votes

# Answer
# Charcoal, 61 bytes

```
ＷＳ⊞υι≔Ｅ⊞Ｏ⁺⟦§υ⁰⟧υ§υ±¹Ｅ⁺⁺§ι⁰ι§ι±¹℅λθＥυ⭆ι℅÷⁺⁴ΣＥ✂θκ⁺³κ¹Σ✂νμ⁺³μ¹¦⁹

```

Try it online! Link is to verbose version of code. Takes input as a list of newline-terminated strings. Explanation:

```
ＷＳ⊞υι

```

Input the string to be blurred.

```
≔Ｅ⊞Ｏ⁺⟦§υ⁰⟧υ§υ±¹Ｅ⁺⁺§ι⁰ι§ι±¹℅λθ

```

Prepend and append a copy of the first and last rows, then for each row, prepend and append a copy of the first and last characters, and convert all of the characters to their code points to create an expanded array.

```
Ｅυ⭆ι℅÷⁺⁴ΣＥ✂θκ⁺³κ¹Σ✂νμ⁺³μ¹¦⁹

```

Map over the original list of strings, replacing each character with the average of the 3×3 tile taken from the expanded array.
> 1 votes

# Answer
# 05AB1E, 19 bytes

```
4Fíø¬š}€ü3ü3εøÇÅAòç

```

I/O as character-matrices.

Try it online or verify all test cases.

**Explanation:**

Step 1: Add the edges and corners as explained in the challenge description:

```
4F            # Loop 4 times:
  íø          #  Rotate once counterclockwise:
  í           #   Reverse each inner row
   ø          #   Zip/transpose; swapping rows/columns
    ¬         #  Push the first row (without popping the matrix)
     š        #  Prepend it
 }            # Close the map

```

Try just this first step online.

Step 2: Create overlapping 3x3 blocks:

```
€             # After the loop: map over each inner row:
 ü3           #  Convert it to a list of overlapping triplets
   ü3         # And then convert these lists to overlapping triplets as well
     ε        # Map over each list of matrices:
      ø       #  Zip/transpose; swapping rows/columns, to create 3x3 blocks

```

Try just the first two steps online.

Step 3: Convert the characters to codepoint integers; get the rounded average of each 3x3 block; and convert these new codepoint integers back to characters (and output as result):

```
       Ç      #  Convert each inner 3x3 block to a flattened list of codepoint integers
        ÅA    #  Get the average of each list
          ò   #  Round each decimal to an integer
           ç  #  Convert this rounded integer back to a character
              # (after which the resulting matrix is output implicitly)

```
> 0 votes

---
Tags: code-golf, string, ascii-art, matrix
---


title: Collatz Conjecture (OEIS A006577)

text:
# Question
Title: Collatz Conjecture (OEIS A006577)
This is the Collatz Conjecture (OEIS A006577):

* Start with an integer *n* \> 1.
* Repeat the following steps:
    + If *n* is even, divide it by 2.
    + If *n* is odd, multiply it by 3 and add 1.

It is proven that for all positive integers up to *5 * 260*, or about *5764000000000000000*, *n* will eventually become *1*.

Your task is to find out how many iterations it takes (of halving or tripling-plus-one) to reach *1*.

Relevant xkcd :)

Rules:

* Shortest code wins.
* If a number \< 2 is input, or a non-integer, or a non-number, output does not matter.

Test cases

```
2  -> 1
16 -> 4
5  -> 5
7  -> 16

```

# Answer
> 19 votes
## GolfScript, ~~24~~ ~~23~~ ~~21~~ ~~20~~ 18 chars

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

```

Assumes input on stdin. Online test

# Answer
> 23 votes
# 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
$>

```

# Answer
> 18 votes
# 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\\$.

# Answer
> 14 votes
## 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

```

# Answer
> 12 votes
# 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

```

# Answer
> 10 votes
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

```

# Answer
> 10 votes
**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.

# Answer
> 10 votes
## 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

```

# Answer
> 9 votes
### 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

```

# Answer
> 8 votes
## 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.

```

# Answer
> 7 votes
### J, 30 characters

```
<:#-:`(1+3&*)`]@.(2&|+1&=)^:a:

```

Turned out quite a bit longer than desired

usage:

```
   <:#-:`(1+3&*)`]@.(2&|+1&=)^:a:2
1
   <:#-:`(1+3&*)`]@.(2&|+1&=)^:a:16
4
   <:#-:`(1+3&*)`]@.(2&|+1&=)^:a:5
5
   <:#-:`(1+3&*)`]@.(2&|+1&=)^:a:7
16
   <:#-:`(1+3&*)`]@.(2&|+1&=)^:a:27
111

```
* `-:`(1+3&*)`]` is a gerund composed of three verbs, used on three occasions. `-:` means "halve", `(1+3&*)` or `(1+3*])` encodes the multiplication step and `]` (identity) aids termination.
* `2&|+1&=` forms an index to the gerund. literally, "the remainder after division by two plus whether it equals one".
* `#verb^:a:` iterates the function until the result is stable (here, forced explicitly), while collecting the steps, then counts them. Stolen from @JB. `<:` decrements the step count by one to align with the question requirements.

# Answer
> 7 votes
## 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

```

# Answer
> 7 votes
# 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.

### Change Made

The above is simply to calculate the Collatz sequence for `n` given an input of the form `2^n`. The only change I made to also keep count of the steps taken was to make the 1/3 from states Q -\> D into an 11/3, 11 being the smallest unused prime. This fraction is only executed once for every number in the sequence; it's the state that figures out whether the number is even or odd to figure out what's next. Therefore, the `11` prime register is incremented once per number in the sequence, except one, yielding the number of steps.

### Note

I simply encoded the state diagram as below and wrote an interpreter which did the dirty work. However, the work done to convert a state diagram to FRACTRAN is also detailed in Conway's article above:

* A: 9/4 -\> T
* T: 4/1 -\> Q
* Q: 7/6\*, 11/3 -\> D, 5/1 -\> R
* R: 3/7\*|Q
* D: 1/3 -\> E, 729/7 -\> M
* M: 10/7\*, 1/3 -\> N, 16/1 -\> O
* N: 7/5\*|M
* E: 2/5\*|A
* O: 1/5\*|A

# Answer
> 6 votes
## APL (31)

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

```

# Answer
> 5 votes
# 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))

```

# Answer
> 5 votes
# 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 :)

# Answer
> 5 votes
## 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:

# Answer
> 5 votes
# 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.

```

# Answer
> 5 votes
# 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

```

# Answer
> 5 votes
# 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.

# Answer
> 5 votes
# 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.

# Answer
> 4 votes
## GolfScript (23 chars)

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

```

Online test

# Answer
> 4 votes
## 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)

```

# Answer
> 4 votes
# 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.

# Answer
> 4 votes
# 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.

# Answer
> 4 votes
# 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.

# Answer
> 4 votes
# 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!

# Answer
> 4 votes
# \>\<\>, 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=?

```

# Answer
> 4 votes
# 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.

# Answer
> 4 votes
# 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!

# Answer
> 3 votes
# Q,46

```
{i::0;{x>1}{i+:1;$[x mod 2;1+3*x;(_)x%2]}\x;i}

```

# Answer
> 3 votes
## 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);
}

```

# Answer
> 3 votes
# 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.

# Answer
> 3 votes
# ~-~! (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.

# Answer
> 3 votes
# 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)

```

# Answer
> 3 votes
# 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).

# Answer
> 3 votes
# \>\<\>, 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;

```

# Answer
> 3 votes
# C (gcc), ~~43~~ 33 bytes

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

```

Try it online!

# Answer
> 3 votes
# 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.

# Answer
> 3 votes
# BitCycle `-u`, 90 bytes

```
 ~  ~!
?v C/v
v<   <
A\\ B^
>/\/C =v
  Cvv  <
  v~v/
  >   ^
  v =
>> >>^
\~~~
 ~v~^
^ + ~

```

Try it online! Or, watch it in action here.

### Algorithm

The main loop starts with the current number \\$n\\$ in unary in the A collector. We divide the number by 2, splitting off two bits at a time; one of the halves, \\$\lfloor \frac n 2 \rfloor\\$, goes into the uppermost C collector; the other half goes into the middle C collector; and the remainder, \\$n\text{ mod }2\\$, goes into the bottom C collector.

Once the number is completely divided up in this way, the C collectors open.

* The top C collector sends a 1 to the sink at the top right, adding 1 to the output, and sends all of its bits back into A.
* If the bottom C collector is empty (i.e. \\$n\text{ mod }2 = 0\\$, i.e. \\$n\\$ was even), the first bit from the middle collector hits the bottommost switch `=` and activates it pointing right, which discards the bits. This leaves A with just the \\$\lfloor\frac n 2\rfloor\\$ bits it got from the top C collector: \\$n\text{ even}\to n/2\\$.
* If the bottom C collector contains a 1 bit (i.e. \\$n\text{ mod }2 = 1\\$, i.e. \\$n\\$ was odd), a negated copy of it hits the bottommost switch and activates it pointing left. This sends the bits from the bottom and middle C collectors into the big collection of dupnegs `~` at the bottom, which makes five copies of its input and discards one bit. All the copies are then sent back into A: \\$n\text{ odd}\to \lfloor\frac n 2\rfloor + 5\left( \lfloor\frac n 2\rfloor + 1\right) - 1 = 6\lfloor\frac n 2\rfloor + 3 + 1 = 3n + 1\\$.

This whole process repeats until \\$n=1\\$, at which point the two halves are 0; this means the only C collector with data is the bottommost one that holds the remainder. The remainder bit is directed up to the uppermost switch `=`. Normally, this switch would have been activated by the bits from the middle C collector already, and the remainder bit would follow them into the 5-times circuitry. But since the middle C collector is empty, the remainder bit passes through the switch and continues northward off the playfield. Since there are no bits remaining on the playfield, the program halts and displays the number of steps taken.

# Answer
> 3 votes
# 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.

# Answer
> 3 votes
# 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!

# Answer
> 3 votes
# Pyth 23byte

```
J0WtQ=Q@,/Q2h*3QQ=JhJ;J

```

# Answer
> 2 votes
## 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))))

```

# Answer
> 2 votes
# 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 :-)

# Answer
> 2 votes
# 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.

# Answer
> 2 votes
# 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

```

# Answer
> 2 votes
## Haskell 73 Bytes 73 Chars

```
r n |even n=n`quot`2
    |otherwise=3*n+1
c=length.takeWhile(/=1).iterate r

```

# Answer
> 2 votes
## 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

```

# Answer
> 2 votes
# 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

```

# Answer
> 2 votes
# 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`

# Answer
> 2 votes
# 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.

# Answer
> 2 votes
# 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.

# Answer
> 2 votes
# 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!

# Answer
> 2 votes
# 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))))))

```

# Answer
> 2 votes
## 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.

```

# Answer
> 2 votes
# 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

```

# Answer
> 2 votes
# *Acc!!*, ~~127~~ 75 bytes

```
Count u while N/49 {
_+1
}
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

```
# Read input in unary
Count u while N/49 {   # Increment u from 0 while input character is >= "1"
  _+1                  # Add one to accumulator
}

# 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

```

# Answer
> 2 votes
# 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))))))

```

# Answer
> 2 votes
# 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.

# Answer
> 2 votes
# Emojicode, 157 bytes

```
➡ac 0▶a 1a 2 0a➗a 2a➕✖a 3 1c➕c 1c 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

```

# Answer
> 2 votes
# 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)

```

# Answer
> 2 votes
# 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!

# Answer
> 2 votes
# Pushy, 24 bytes

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

```

Try it online!

# Answer
> 2 votes
# 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

```

# Answer
> 2 votes
# 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!

# Answer
> 2 votes
# 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.

# Answer
> 2 votes
# 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*.

# Answer
> 2 votes
# Julia 1.0, 29 bytes

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

```

Try it online!

Based on Dennis' answer

# Answer
> 2 votes
# 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!

# Answer
> 2 votes
# 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

```

# Answer
> 1 votes
# 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.

# Answer
> 1 votes
# 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.

# Answer
> 1 votes
# 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**

# Answer
> 1 votes
# 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

```

# Answer
> 1 votes
# Mathcad, 36 "bytes"

From user perspective, Mathcad is effectively a 2D whiteboard, with expressions evaluated from left-to-right,top-to-bottom. Mathcad does not support a conventional "text" input, but instead makes use of a combination of text and special keys / toolbar / menu items to insert an expression, text, plot or component. For example, type ":" to enter the definition operator (shown on screen as ":=") or "ctl-\]" to enter the while loop operator (inclusive of placeholders for the controlling condition and one body expression). What you see in the image above is exactly what appears on the user interface and as "typed" in.

For golfing purposes, the "byte" count is the equivalent number of keyboard operations required to enter an expression.

# Answer
> 1 votes
## 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

```

# Answer
> 1 votes
# 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.

# Answer
> 1 votes
# 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)))))

```

# Answer
> 1 votes
## C, 38 bytes

```
g(v){return v^1?1+g(v&1?v*3+1:v/2):0;}

```

# Answer
> 1 votes
# 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

```

# Answer
> 1 votes
# 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;
}

```

# Answer
> 1 votes
# 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.

# Answer
> 1 votes
# Attache, 11 bytes

```
CollatzSize

```

Try it online!

Not much to say...

# Answer
> 1 votes
## 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@

```

# Answer
> 1 votes
# Japt, ~~18~~ 15 bytes

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

```

Try it

# Answer
> 1 votes
# 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.

# Answer
> 1 votes
## 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
}

```

# Answer
> 1 votes
# 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.

# Answer
> 1 votes
# 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.

# Answer
> 1 votes
# 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(...)

```

# Answer
> 1 votes
# JavaScript, 35 bytes

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

```

Try it online!

# Answer
> 1 votes
# Keg `-rR`, 23 bytes (SBCS)

I really need to remember those new instructions.

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

```

Try it online!

# Answer
> 1 votes
# 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
}

```

# Answer
> 1 votes
# 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!

# Answer
> 1 votes
# 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!

# Answer
> 1 votes
# 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.

# Answer
> 1 votes
# 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!

# Answer
> 1 votes
# 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)

# Answer
> 1 votes
# 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

```

# Answer
> 1 votes
# 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!

# Answer
> 1 votes
```
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

```

# Answer
> 1 votes
# 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
}

```

# Answer
> 1 votes
# Vyxal, ~~17~~ ~~12~~ 11 bytes

```
∷[T›|½)İ2ḟ⇧

```

Try it Online!

*-5 bytes thanks to lyxal*

Removed flag thanks to emanresu A.

# Answer
> 1 votes
# 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

# Answer
> 1 votes
# 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!

# Answer
> 1 votes
# Factor \+ `project-euler.014`, 22 bytes

```
[ collatz length 1 - ]

```

Try it online!

# Answer
> 1 votes
# 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)

```

# Answer
> 1 votes
# brev, 71 bytes

```
(rec(f x)(cond((= x 1)0)((odd? x)(+(f(+(* 3 x)1))1))(1(+(f(/ x 2))1))))

```

# Answer
> 1 votes
# 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

```

# Answer
> 1 votes
# 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

```

# Answer
> 1 votes
# 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

```

# Answer
> 1 votes
# 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

```

# Answer
> 0 votes
# 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

```

# Answer
> 0 votes
# 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.

# Answer
> 0 votes
# 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);}

```

# Answer
> 0 votes
# 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!

# Answer
> 0 votes
# 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);

```

# Answer
> 0 votes
# SmileBASIC, 54 bytes

```
INPUT N
WHILE N-1D=1AND N
C=C+1N=N*3*D+D+N/2*!D
WEND?C

```

# Answer
> 0 votes
# 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

```

# Answer
> 0 votes
# 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.

# Answer
> 0 votes
# Emojicode, 139 bytes

```
➡ai 0❎1a1a 2a➕1✖3aa➗a 2i➕1ii

```

Try it online!

# Answer
> 0 votes
# 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!

# Answer
> 0 votes
# 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 .

# Answer
> 0 votes
# 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!

# Answer
> 0 votes
# 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;

```

# Answer
> 0 votes
# 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

```

# Answer
> 0 votes
# 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!

# Answer
> 0 votes
# Ahead, 38 bytes

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

```

Try it online!

# Answer
> 0 votes
# 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

```

# Answer
> 0 votes
# 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`.

# Answer
> 0 votes
# 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)))

```

# Answer
> 0 votes
# 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

# Answer
> 0 votes
# 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

```

# Answer
> 0 votes
# Knight, 37 bytes

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

```

Try it online!

# Answer
> 0 votes
# \>\<\> (Fish), 31 bytes

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

```

Try it

# Answer
> 0 votes
# 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:

```

```

---
Tags: code-golf, math, sequence
---