title: 1, 2, miss a few, 99, 100

text:
# Question
Title: 1, 2, miss a few, 99, 100
When I was a kid, there was a "really cool" shortcut to count to 100:

`1, 2, miss a few, 99, 100`

Output the exact string above, in the fewest characters possible, without using these characters: `0`, `1`, `2`, `9`

# Answer
# JavaScript (ES6), 43 bytes

Browser only.

```
_=>atob`MSwgMiwgbWlzcyBhIGZldywgOTksIDEwMA`

```

Try it online! (with a polyfill)

---

# JavaScript (ES6), 45 bytes

```
_=>[4-3,5-3,'miss a few',33*3,5*5*4].join`, `

```

Try it online!
> 23 votes

# Answer
# Bash \+ coreutils, 40

```
tr 3-? /-:<<<"5, 6, miss a few, ==, 544"

```

Try it online!
> 17 votes

# Answer
# , ~~43~~ 41 bytes

```
cat(T+F:T,"miss a few",3*33+F:T,sep=", ")

```

Try it online!

`T` and `F` are equal to `TRUE` and `FALSE`. They get coerced to integers `1` and `0` by the operators `+` and `:`.
> 15 votes

# Answer
# Python 3, ~~54~~, ~~51~~, ~~47~~ 42 bytes

Saved **2 bytes** thanks to Digial Trauma's suggestion to replace `8*8+35 = 99` with `33*3 = 99`.

Saved **1 byte** by realizing that I could replace `8*8+36 = 100` with `4*5*5 = 100`.

Saved **4 bytes** thanks to dingledooper's suggestion to use `sep=', '` in the `print`!

Saved **5 bytes** thanks to ovs' suggestion to use `bytes` objects.

## New Answer

```
print(*b"","miss a few",*b"cd",sep=", ")

```

```
The b"" is equivalent to b"\1\2".

```

Try it online!

## Old Answer:

```
print(f"{4-3}, {6-4}, miss a few, {33*3}, {4*5*5}")

```

Try it online!
> 11 votes

# Answer
# Jelly, 23 bytes

```
3Ṗ,³ṭ’¤j“¤mɗʂɠẉ⁾»W¤j⁾,

```

Try it online!

## How it works

One thing to note: Jelly has the  atom, which prints a string Jelly representation of it's argument. Lists in Jelly do not use `[` and `]` as open/close markers, instead they consist of comma-separated values:

```
1,2,3,4,5Ṙ

```

prints `1,2,3,4,5`, unfortunately, without spaces.

```
3Ṗ,³ṭ’¤j“¤mɗʂɠẉ⁾»W¤j⁾,  - Main link. Takes no arguments
3                       - Yield 3;
 Ṗ                      - Pop from 3, yielding [1, 2]
      ¤                 - Group the previous links into a nilad:
   ³                    -   100
     ’                  -   Decrement; 99
    ṭ                   -   Tack; [99, 100]
  ,                     - Pair; [[1, 2], [99, 100]]
                  ¤     - Group the previous links into a nilad:
        “¤mɗʂɠẉ⁾»       -   The compressed string "miss a few"
                 W      -   Wrap; ["miss a few"]
       j                - Join; [1, 2, ["miss a few"], 99, 100]
                   j⁾,  - Join with ", "; "1, 2, miss a few, 99, 100"

```
> 10 votes

# Answer
# HTML + CSS, 118 bytes

```
<c>, <c>, miss a few, <d><d><c>, <c><style>c:before{content:counter(a);counter-increment:a}d{counter-increment:a 48}
```
> 10 votes

# Answer
# Ruby, 42 bytes

```
$><<[3/3,6/3,'miss a few',33*3,5*5*4]*", "

```

Try it online!

-4 from Jonah. Borrows from Arnauld's answer.

# Ruby, <sup>~~46~~</sup> 44 bytes

```
$><<"cd".bytes.insert(2,"miss a few")*", "

```

Try it online!

The three unprintables for codepoints 1, 2 and 3 are in the string containing "cd".

-2 from manatwork. Other version with same bytecount
> 8 votes

# Answer
# PHP, ~~57~~ ~~56~~ 53 bytes

```
printf('%c, %d, miss a few, %d, %o',7*7,5-3,33*3,64);

```

Try it online!

A `printf`, some spices, stir

EDIT: -1 byte thanks to Digital Trauma

EDIT 2: -3 bytes thanks to Michael Dorgan for octal, thought about 153 with `%x` for hex but it has a 1..

**Also, less fun but 2 bytes shorter by manatwork, improved by BadHorsie (it seems that `<?=` can also take multiple arguments with comas):**

# PHP, ~~51~~ 49 bytes

```
<?=5-4,', ',5-3,', miss a few, ',33*3,', ',5*5*4;

```

Try it online!
> 8 votes

# Answer
# Whispers v3, ~~124..120~~ 114 bytes

```
>> Each 5 57
>> Then 7 3 6 3 4 3 54 3 8
> ", "
> "miss a few"
>> "L"
>> #3
>> #5
>> 53*6
>> #4
>> 8-7
>> Output 56

```

Try it online!

**Explanation:**

I use the fact that each line with the line number \\$x\\$ can be called with \\$x + k \cdot n \\$, where \\$k \in \mathbb{N} \\$ and \\$n\\$ is total number of lines of code. Example from code with 11 lines: the reference to line `1` can be replaced by `12`, `23`, `34`, and so on.

Try the translated version online!

**Line by line:**

As always in Whispers, we run the last line first:

```
>> Output 56

```

This line outputs the result from line 56. Since the code does not have 56 lines it actually outputs line \\$ 56 \mod 11 = 1\\$:

```
>> Each 5 57

```

Applying the same trick again we can replace this line with:

```
>> Each 5 2

```

In line 5 we can expect a function and in line 2 an array. The function will be applied on each element of the array and it replaces the element with the result. Let us first look at line 5:

```
>> "L"

```

`L` is an argument from the `Each` statement in line 1. `L` is converted to a string.

Now line 2:

```
>> Then 7 3 6 3 4 3 54 3 8

```

`Then` creates an array with the arguments as its elements. If we would print this line we get the following array:

```
[1, ', ', 2, ', ', 'miss a few', ', ', 99, ', ', 100]

```

**Explanation of the arguments:**

Line 3 and 4: simple strings

Line 6: Returns the length of line 3, so we get `2`

Line 7: Returns the length of line 5, so we get a `1`

Line 8: Returns the result of line 53 (actually 9) raised to the power of the result of line 6, so we get `100`

Line 54 (actually 10): Subtracts result of line 8 with the result of line 7, so we get a `99`
> 8 votes

# Answer
# C (gcc), ~~54~~ 56 bytes

```
l(){printf("%c, %d, miss a few %d, %o",7*7,5-3,'c',64);}

```

Try it online!

Let's save a couple bytes using Octal for the 100. Thanks to Sheik Yerbouti for saving a byte and point out the no commas issue.
> 6 votes

# Answer
# , 52 bytes

```
cat(chartr("@-K","/-:","B, C, miss a few, JJ, BAA"))

```

Try it online!

Encodes numbers as uppercase letters and then applies character range translation. Since we can't directly type `0-9`, we expand the range by 1 character in both directions resulting in `/-:`.
> 5 votes

# Answer
# brainfuck, 146 bytes

```
-[----->+>+>+>++>++<<<<<]>>>--.-----.------------.<-.------.>.>+++++++.>+++.<++++++..<.>>--------.<<.>>+++++.-.<++++.<<.>.<<++++++..>.>.<+++++.-..

```

Try it online!

A fairly straightforward 255/5=51 loop giving ASCII 51 and ASCII 102 as `333ff` in 5 consecutive cells, followed by hunt and peck strategy.
> 5 votes

# Answer
# Perl 5, 42 bytes

```
$,=", ";say!!3,5-3,"miss a few",3*33,4*5*5

```

Sets the record separator, and prints a few numbers and a string.

Try it online!

# Perl 5, 43 bytes

```
say"C, D, miss a few, KK, CBB"=~y,A-L,/-:,r

```

Translates B-K to 0-9 (extended by one more ASCII code on each side of the range) and prints.

Try it online!

# Perl 5, 44 bytes

```
$,=", ";say unpack"c3/acc","
miss a fewcd"

```

Sets the record separator, and unpacks values to be printed.

Try it online!
> 5 votes

# Answer
# Julia, 41 bytes

```
()->join([b"";"miss a few";b"cd"],", ")

```

Try it online!

the first string is `"\1\2"` which is allowed if I understand the challenge correctly

`b"str"` converts the string in an array of the value of each character so `b"\1\2" => [1,2]` and `b"cd" => [99,100]`
> 4 votes

# Answer
# Husk, 31 bytes

```
mȯ←←←"4/#5/#plvv#d#ihz/#<</#433

```

Try it online!

Explanation:

```
m                                 Map the function...
 ȯ←←←                             Decrement character 3 times
      "4/#5/#plvv#d#ihz/#<</#433  desired string "ASCII-shifted" by 3

```
> 4 votes

# Answer
# Jelly, 22 bytes

```
³ḊĖ.ịṚj“¤mɗʂɠẉ⁾»W¤j⁾,

```

A full program that prints the result.

**Try it online!**

### How?

```
³ḊĖ.ịṚj“¤mɗʂɠẉ⁾»W¤j⁾,  - Link: no arguments
³                      - 100
 Ḋ                     - dequeue -> [2,3,...,99,100]
  Ė                    - enumerate -> [[1,2],[2,3],...,[98,99],[99,100]]
   .                   - 0.5
    ị                  - index into -> [[99,100],[1,2]]
     Ṛ                 - reverse
                 ¤     - nilad followed by links as a nilad:
       “¤mɗʂɠẉ⁾»       -   dictionary compression of "miss a few"
                W      -   wrap in a list  -> ["miss a few"]
      j                - join              -> [1,2,"miss a few",99,100]
                   ⁾,  - ", "
                  j    - join              -> [1,", ",2,", ","miss a few",", ",99,", ",100]
                       - implicit print    -> `1, 2, miss a few, 99, 100`

```
> 4 votes

# Answer
# Stax, 20 19 17 bytes

saved 2 bytes thanks to Razetime

```
ü←φr5╧wL'•↔♦$▒ò╠‼

```

Run and debug it

Original brain-dead solution for reference purposes only:

# Stax, 22 bytes

```
ü2Φÿßbÿ»f╙m¡6¿₧|░╘;┬u»

```

Run and debug it
> 4 votes

# Answer
# C++, 56 bytes

```
[]{for(int x:"4/#5/#plvv#d#ihz/#<</#433"s)putchar(x-3);}

```

Inspired by a comment.

Usage:

```
#include <string>
#include <stdio.h>

using namespace std;

int main() {
    auto k = [](){for(int x:"4/#5/#plvv#d#ihz/#<</#433"s)putchar(x-3);};
    k();
    return 0;
}

```

Try it online!
> 4 votes

# Answer
# 05AB1E, 16 bytes

I don't think this would be shorter with `0`, `1`, `2` and `9`.

```
XY…š§€…†Óт<т„, ý

```

Try it online!

```
X                # push 1
 Y               # push 2
  …š§€…†Ó        # push compressed dictionary string "miss a few"
         т<      # push 100-1
           т     # push 100
            „,   # push string ", "
               ý # join the stack with this string

```
> 4 votes

# Answer
# Barrel, 31 34 bytes

```
+n, +n, 'miss a few, '#44+#45+n, +n

```

This is my own esolang, follow the link for more info.

Increments the accumulator, prints it, implicitly prints some strings (`,` and `miss a few,` are implicitly printed), does a loop on accumulator incrementation, and finishes as it started.

Edit: I realized that "97" used a "9". *smacks forehead*
> 4 votes

# Answer
# Retina 0.8.2, 32 bytes

```

B, C, miss a few, JJ, BAA
T`L`d

```

Try it online! Explantion:

```

B, C, miss a few, JJ, BAA

```

Replace the empty input with the literal string.

```
T`L`d

```

Transliterate upper case letters to digits.
> 3 votes

# Answer
# PowerShell (ASCII answer), 128 bytes

```
$k=3-3;((@(46+3),@(53-3),@('miss a few'),@(57,57),@((46+3),48,48))|%{$k++;if($k-eq3){$_}else{($_|%{[char]$_})-join''}})-join', '

```

Try it online!

# PowerShell (Base64 one), 135 bytes

```
[Text.Encoding]::Unicode.GetString([Convert]::FromBase64string('MQAsACAAMgAsACAAbQBpAHMAcwAgAGEAIABmAGUAdwAsACAAOQA5ACwAIAAxADAAMAA='))

```

Try it online!
> 3 votes

# Answer
# Jelly, 23 bytes

```
“×ƤṪ5Ġpṃ:Ƒ5ṫȷØJkxXp⁺¥ġ»

```

Try it online!

Same length as caird's answer, much more boring.
> 3 votes

# Answer
# Python 2, 59 bytes

```
print ', '.join(map(str,(4-3,5-3,'miss a few',33*3,5*5*4)))

```

Try it online!

Thanks to @arnauld for js answer
> 3 votes

# Answer
# Vyxal, ~~21~~ ~~20~~ 19 bytes

```
3ɽ÷«eeȮǒḋp«₁‹₁W‛, j

```

Try it Online!

## Explained

```
3ɽ÷      # stack = [1, 2]
«eeȮǒḋp« # stack = [1, 2, "miss a few"]
₁‹₁      # stack = [1, 2, "miss a few", 99, 100]
W‛, j    # join stack on ", "

```
> 3 votes

# Answer
# Pyth, 29 bytes

```
j+\,d[=hZhZ"miss a few"t=*TTT

```

Try it online!

---

Python 3.8 translation:

```
Z=0
T=10

print(", ".join(map(str,[(Z:=Z+1),Z+1,"miss a few",(T:=T*T)-1,T])))

```
> 3 votes

# Answer
# PHP, 48 bytes

```
<?=join(', ',[!'',~-3,'miss a few',33*3,45^73]);

```

Try it online!
> 3 votes

# Answer
# Vim, 37 keystrokes

```
i3, 3, miss a few, 8, <esc>|<C-x><C-x>l.l<C-a>ylp$pp<C-a>

```
> 3 votes

# Answer
# PHP, 58 54 bytes

```
<?=join(', ',[$i=3/3,++$i,'miss a few',$i=33*3,++$i]);

```

PHP doesnt really want to be typed short, but I liked coming up with this :)
> 3 votes

# Answer
# Perl 6, 45 bytes

```
say join ", ",5-4,5-3,"miss a few",3*33,4*5*5

```

Try it online!
> 3 votes

# Answer
# CJam, ~~28~~ ~~26~~ 25 bytes

*Two bytes off thanks to @Lyxal, and one off thanks to @Lynn!*

```
XY"miss a fewc")i_)]", "*

```

**Try it online!**

### Explanation

```
X              e# Push contents of variable X (predefined value): 1
Y              e# Push contents of variable Y (predefined value): 2
"miss a fewc"  e# Push this string
)              e# Detach the last character from that string
i              e# Convert to integer: gives 99
_)             e# Duplicate, increment: gives 100
]              e# Concatenate stack contents into an array
", "           e# Push this string
*              e# Join the array entries with the specified string
               e# Implicit display

```
> 2 votes

# Answer
# Standard ML (MLton), 65 bytes

```
print(String.map(fn c=>chr(ord c-3))"4/#5/#plvv#d#ihz/#<</#433");

```

Try it online!

`"4/#5/#plvv#d#ihz/#<</#433"` is `"1, 2, miss a few, 99, 100"` shifted by adding three to each ASCII code. `String.map(fn c=>chr(ord c-3))` reverses this shifting by substracting three of each char's `ord`inal number.
> 2 votes

# Answer
# Yabasic, 46 bytes

```
?5-4,", ",5-3,", miss a few, ",33*3,", ",5*5*4

```

Try it online!

Replaced calculated numbers for 1 and 2 with \x hex codes for ASCII 49 and 50 and saved 3 bytes!

(Can't do the above because it results in \x31 and \x32 which of course contain 1 and 2...)
> 2 votes

# Answer
### x86\_16 machine code, 146 bytes

Thank's to @mik for tips and trick :))

Replace : `add al, "0"` / `add dl, "0"` with `add al, 2fh` \+ `inc al` and `add dl, 2fh` \+ `inc dl` to avoid `"0"` in the source code.

```
B3 04          MOV BL, 4
B1 03          MOV CL, 3
2A D9          SUB BL, CL
B4 0E          MOV AH, 0EH
8A C3          MOV AL, BL
04 2F          ADD AL, 2FH
FE C0          INC AL
CD 10          INT 10H
B0 2C          MOV AL, ","
CD 10          INT 10H
80 C3 2F       ADD BL, 2FH
FE C3          INC BL
FE C3          INC BL
8A C3          MOV AL, BL
CD 10          INT 10H
B8 2C 0E       MOV AX, 0E2CH
CD 10          INT 10H
B4 09          MOV AH, 09h
BA 7A 01       MOV DX, OFFSET TXT
CD 21          INT 21H
B8 2C 0E       MOV AX, 0E2CH
CD 10          INT 10H

B8 20 0E       MOV AX, 0E20H
CD 10          INT 10H

B0 21          MOV AL, 33
B3 03          MOV BL, 3
F6 E3          MUL BL
B3 0A          MOV BL, 10
33 C9          XOR CX, CX
           LOOP1:
33 D2          XOR DX, DX
F7 F3          DIV BX
52             PUSH DX
41             INC CX
85 C0          TEST AX, AX
75 F6          JNZ LOOP1
    PRINT_DIGIT1:
5A             POP DX
80 C2 2F       ADD DL, 2FH
FE C2          INC DL
B4 02          MOV AH, 02H
CD 21          INT 21H
E2 F6          LOOP PRINT_DIGIT1

B8 2C 0E       MOV AX, 0E2CH
CD 10          INT 10H
B8 20 0E       MOV AX, 0E20H
CD 10          INT 10H

B0 04          MOV AL, 4
B3 05          MOV BL, 5
F6 E3          MUL BL
F6 E3          MUL BL
B3 0A          MOV BL, 10
33 C9          XOR CX, CX
           LOOP2:
33 D2          XOR DX, DX
F7 F3          DIV BX
52             PUSH DX
41             INC CX
85 C0          TEST AX, AX
75 F6          JNZ LOOP2
    PRINT_DIGIT2:
5A             POP DX
80 C2 2F       ADD DL, 2FH
FE C2          INC DL
B4 02          MOV AH, 02H
CD 21          INT 21H
E2 F6          LOOP PRINT_DIGIT2
            EXIT:
B8 00 4C       MOV AX, 4C00H
CD 21          INT 21H

20 6D 69 73 73 20 61 20 66 65 77 24   TXT DB " miss a few$"

```

Run is DOSBox :
> 2 votes

# Answer
# Elixir, ~~58~~ 49 bytes

```
[?b-?a,?c-?a,"miss a few",?c,?d]|>Enum.join(", ")

```

Try it online!
> 2 votes

# Answer
# Javascript (ES6), 70 bytes

Old 75:

```
a=8-7;b=8-6;c=8-8;d=4+5;_=>`${a}, ${b}, miss a few, ${d}${d}, ${a}${c}${c}`

```

New 50:

```
_=>[8-7,8-6,'miss a few',(4+5)*(5+5)+4+5,(8-7)*(55+55-5-5)].join(', ')

```

by far not the best js answer, ill widdle.
> 2 votes

# Answer
# factor, ~~66~~ 61 bytes

Shaved 5 bytes thanks to @Bubbler!

```
4 3 - 5 3 - 33 3 * CHAR: d "%d, %d, miss a few, %d, %d"printf

```

Try it online!

Original version:

```
4 3 - 5 3 - 33 3 * dup 3 - 4 + "%d, %d, miss a few, %d, %d" printf

```

My first factor line. Probably can be shorter…

Try it online!
> 2 votes

# Answer
# Zsh, 47 bytes

Not very creative. Oh well.

```
echo $[3/3], $[6/3], miss a few, $[##c], $[##d]

```

Try it online!
> 1 votes

# Answer
# Charcoal, 21 bytes

```
”'3?Sxv7´Ｄ｜λ*§ξ¬Ｅ‹Ｄαg

```

Try it online! Compression again. Best I could do without compression is 23 bytes:

```
⪫⟦ＬψＬχmiss a few℅c℅d⟧,

```

Try it online! Link is to verbose version of code.
> 1 votes

# Answer
# Deadfish~, ~~187~~ 178 bytes

```
{iiiii}dcdddddc{d}ddc{ii}ddcddddddc{d}ddc{{i}dd}dddcddddc{i}cc{{d}ii}dddc{{i}dddd}iiiiic{{d}iiii}dddddc{{i}ddd}cdc{i}{i}ddc{{d}iii}dddddc{d}ddc{ii}iiiiicc{d}dddc{d}ddc{ii}dddcdcc

```

The previous version was bad.

Try it online!
> 1 votes

# Answer
# BRASCA, ~~41~~ 36 bytes

```
`<0x01>, <0x02>, miss a few, `I,[o]H{n` ,`ooHn

```

Replace \<0x01\> and \<0x02\> with ascii codepoints 1 and 2.

Try it!
> 1 votes

# Answer
# PHP, 30 bytes

This contains unprintables so the link is to a Bash program that reconstructs the file and validates it.

```
<?=~.........................;

```

Try it online!

## Explanation

`print`s the bitflipped (`~`) string `1, 2, miss a few, 99, 100`.
> 1 votes

# Answer
# Rust, 68 Bytes

```
fn main(){print!("{}, {}, miss a few, {}, {}",4-3,5-3,66+33,63+37)}

```

This is my first attempt at code golf Yahoo! Try it online

# Rust, 56 bytes

Cutting out the main{} on tio saves 12 bytes

```
print!("{}, {}, miss a few, {}, {}",4-3,5-3,66+33,63+37)

```

Try it online!
> 1 votes

# Answer
# AWK, 53 bytes

```
$a=++x", "++x", miss a few, "(z=(++y y)-x)z", "++z--y

```

Try it online!

This abuses a couple of AWK language features, including that all variables are initialized to blank/0/False (context sensitive), that it will happily convert strings to numeric values to make an arithmetic operator work, and it will also convert numeric values to strings in order to append characters to it.

First it gets `1,`  by incrementing variable `x`

```
++x", "

```

then `2, miss a few,`  just does the same thing again...

```
++x", miss a few, "

```

getting a `9` is a bit more work,

```
(++y y)-x

```

which works by getting a `1` with `++y` then appended it to itself to get `11` then subtracting `2` with `-x`.

Using that to set the variable `z` means we can appended another `9` on the end with,

```
(z=...)z

```

That just leaves the last bit `, 100` which we can get by incrementing the `9` and appending to that `1` decremented.

```
", "++z--y

```

I'm pretty sure there are other ways to do this in AWK that are shorter, but I like that this doesn't use any numbers.

One last thing I forgo to mention... The string is printed since,

```
$a=...

```

is interpreted as `$0=...` which evaluates to True, causing AWK print the value of `$0`, which was just set to the output we want.
> 1 votes

# Answer
# APL (Dyalog Unicode), 45 bytes

```
(5↓7⌽∊'miss a few, ',⍨(', ',⍨⍕)¨5↑(3-5)⌽⍳77+!4)

 5↓ ⍝ Drop the first 5 elements
   7⌽ ⍝ Rotate left 7
     ∊'miss a few, ', ⍝ Concatenate and enlist
       ⍨ ⍝ Swap arguments
         (', ',⍨⍕)¨ ⍝ Encode as character and concatenate after swapping arguments
           5↑ ⍝ Take the first 5 elements
             (3-5)⌽ ⍝ Rotate right 2
               ⍳77+!4 ⍝ Create range from 0–100 inclusive

```

Try it online!
> 1 votes

# Answer
# GolfScript, 34 bytes

```
!.)', ':c.@\'miss a few'3c\33*.c\)

```

Try it online!

```
!                                   Push 1 to the stack.
 .)                                 Copy the 1 and increment.
   ',':c                            Define c as ', ' to save characters when commas are needed.
        .@\                         Copy the ', ' and move stuff around into the right order.
           'miss a few'             Push the string to the stack.
                       3c\          Push 3 and ', ' then swap them.
                          33*       Multiply 3*33 to get 99.
                             .c\)   Copy the 99, push ', ' then swap them and increment the last 99.

```
> 1 votes

# Answer
# Arn, 22 bytes

```
˜▒çc>åžî¼#(¸“├)øW§Ò┴Ì"

```

Try it!

# Explained

Just the string literal. Pretty boring, the next-shortest I could get without this was 29 bytes.
> 1 votes

# Answer
# PHP, 69 bytes

```
<?=55-54,', ',floor((5*4)/7),', ','miss a few ',64746/654,', ',5*5*4;

```
> 1 votes

# Answer
# Scratch, 110 bytes

Try it online!

Easy sauce. Alternatively, 12 blocks.

```
when gf clicked
say(join((4)-(3))(join[, ](join((5)-(3))(join[, miss a few, ](join((3)*(33))(join[, ]((66)+(34

```
> 1 votes

# Answer
# AWK, 49 bytes

```
END{print++x", "5-3", miss a few, "3*33", "4*5*5}

```

Assuming empty input (otherwise change `END` to `BEGIN` for a 51-byte answer).

Try it online!
> 1 votes

# Answer
# Python 3, 56 bytes

```
lambda:f"{3//3}, {8//4}, miss a few, {3*4*8+3}, {4*5*5}"

```

Try it online! Uses basic math and an f-string to get the job done.
> 1 votes

# Answer
# Pip, 23 bytes

```
[o#k"miss a few"h+vh]Jk

```

Try it online!

having a builtin for `,`  is sadly not enough

-3 bytes from DLosc.
> 1 votes

# Answer
# Japt, 22 bytes

```
Cì p`ÚÍ a few`#cL qSi,

```

Test it

```
Cì p`...`#cL qSi,
C                     :12
 ì                    :To digit array
   p                  :Push
    `...`             :  Compressed string "miss a few"
         #c           :  Charcode of "c" (99)
           L          :  100
             q        :Join with
              S       :  Space
               i,     :  Prepended with a comma

```
> 1 votes

# Answer
# Haskell, 54 bytes

```
p=pred
main=putStr$p.p.p<$>"4/#5/#plvv#d#ihz/#<</#433"

```

Try it online!
> 1 votes

# Answer
# MathGolf, ~~23~~ 22 bytes

```
)└"miss a few"♀┐\]û, u

```

Try it online.

**Explanation:**

```
)                      # +1 (since the stack is empty, it'll use an implicit 0)
 └                     # Push the top of the stack + 1 (without popping)
  "miss a few"         # Push string "miss a few"
              ♀        # Push 100
               ┐       # Push the top of the stack - 1 (without popping)
                \      # Swap the top two values on the stack
                 ]     # Wrap all values on the stack into a list
                  û,   # Push string ", "
                     u # Join the list with this ", " as delimiter
                       # (after which the entire stack is output implicitly as result)

```

Even if we were allowed to use `0129`, the byte-count would remain the same (the `)└` could simply be `12`).
> 1 votes

# Answer
# Java (JDK), 52 bytes

```
i->4-3+", "+(5-3)+", miss a few, "+(33*3+", "+5*5*4)

```

Try it online!
> 1 votes

# Answer
# \>\<\>, 44 bytes

```
68*:77*' ,>'5-:' ,wef a ssim ,':6+' ,':5+>o<

```

Try it online!
> 1 votes

# Answer
# Knight, 50 bytes

```
O+++++++''-6 5', '-6 4', miss a few, 'A'c'', 'A'd'

```

Try It Online!

Probably not optimal but whatever.
> 1 votes

# Answer
# GNU dc, 41 bytes

```
Kzn[, ]nzzn[, miss a few, ]n33z*dn[, ]n+n

```

Try it online!
> 1 votes

# Answer
# C#, 74 bytes

```
using System;Console.Write($"{4-3}, {5-3}, miss a few, {33*3}, {64*4:X}");

```
> 1 votes

# Answer
# YASEPL, ~~60~~ 54 chars

```
=a)commaſspace=b$48+›#a+›#a#"miss a few"#a+7››#a-8›-››

```

if you're wondering, this is a pretty stupid esolang I made a while ago in Node.JS
> 1 votes

# Answer
# TeX, 41 bytes

In TeX you can print the ASCII-value of a character using `\number`CHAR`.

```
\def~{\number`}~^A, ~^B, miss a few, ~c, ~d

```

Replace `^A` and `^B` in the above code with SOH and STX.

Using just the printable range of ASCII, the following works as well without modifications (4 bytes more):

```
\def~{\number`}~^^A, ~^^B, miss a few, ~c, ~d

```

Complete TeX file:

```
\def~{\number`}~, ~, miss a few, ~c, ~d
\bye

```

---

<sup>To copy the code above (the complete file), hit on the edit-button, so that you can copy the unprintable ASCII-letters, which are displayed in the editor.</sup>
> 0 votes

# Answer
**C++17**

```
#include <iostream>
main()
{
  std::cout << 4 - 3 << ", " << 5 - 3 << ", miss a few, " << 33 * 3 << ", " << 5 * 5 * 4 << "\n";
}

```
> 0 votes

# Answer
# Templates Considered Harmful, 129 bytes

```
Cat<Cat<Cat<Cat<Cat<T,St<44,' '>>,Add<T,T>>,St<44,' ','m','i','s','s',' ','a',' ','f','e','w',44,' ',57,57,44,' '>>,T>,St<48,48>>

```

Try it online!

Tries to represent each character as its ascii value. If that contains a forbidden number, replace it with its char literal. This only leaves `1` and `2` to deal with.

`1` is replaced with `T`, which evaluates to `I<1>` which is cast into string `1` when concatenated.
`2` is replaced with `Add<T,T>`, which evaluates to `I<2>` which is cast into string `2` when concatenated.

```
Cat<
 ...
     T,                                                                    # "1"
     St<44,' '>>,                                                          # ", "
    Add<T,T>>,                                                             # "2"
   St<44,' ','m','i','s','s',' ','a',' ','f','e','w',44,' ',57,57,44,' '>>,# ", miss a few, 99, "
  T>,                                                                      # "1"
 St<48,48>>                                                                # "00"

```
> 0 votes

# Answer
# x86 opcode, ~~42~~ 41 bytes

```
BE 8F 81 04 08 29 C9 B1 | 1A AC 04 6E AA E2 FA C3
BE B2 C4 BE B2 FF FB 05 | 05 B2 F3 B2 F8 F7 09 BE
B2 CB CB BE B2 C3 C2 C2 | 92

```

```
fun:	mov esi, src
	sub ecx, ecx
	mov cl, srcEnd-src
x:	lodsb
	add al, '1'-0xC3
	stosb
	loop x
src:	ret
	db ', 2, miss a few, 99, 100', 0
srcEnd:
repeat srcEnd-src-1
	load a byte from src+%
	store byte (a-'1'+0xC3) and 0xFF at src+%
end repeat
funEnd:

```

Try it online!

Function that output to \[esi\] assuming enough space, should be placed on right place such that `src` contain no invalid chars
> 0 votes

# Answer
# CSASM v2.1.1, 145 bytes

```
func main:
push 4
push 3
sub
push ", "
add
push 5
push 3
sub
add
push ", miss a few, "
add
push 33
push 3
mul
add
push ", "
add
push 5
dup
mul
push 4
mul
add
print
ret
end

```

**Commented:**

```
func main:
    ; Push 4 - 3
    push 4
    push 3
    sub
    ; String concatenation:  1 + ", "
    push ", "
    add
    ; Push 5 - 3
    push 5
    push 3
    sub
    ; String concatenation:  "1, " + 2
    add
    push ", miss a few, "
    ; String concatenation:  "1, 2" + ", miss a few, "
    add
    ; Push 33 * 3
    push 33
    push 3
    mul
    ; String concatenation:  "1, 2, miss a few, " + 99
    add
    push ", "
    ; String concatenation:  "1, 2, miss a few, 99" + ", "
    add
    ; Push a 5 and multiply it by itself
    push 5
    dup
    mul
    ; Push 25 * 4
    push 4
    mul
    ; String concatenation:  "1, 2, miss a few, 99, " + 100
    add
    ; Print the value on the top of the stack:
    ;   Stack: [ "1, 2, miss a few, 99, 100" ]
    print
    ret
end

```
> 0 votes

# Answer
# Pxem, Filename: 32 bytes + Content: 4 bytes = 36 bytes, depends on ASCII-compatible.

* Filename (escaped unprintables): `\001.n.e\002.n.emiss a few.p.ec.n.ed.n`
* Content: `, .p`

Try it online!

## How it works

* Pxem is a stack-based procedure language.
* `.n` is `printf("%d",pop) unless empty`.
* `.e` calls subroutine (which is content).
* `.p` is `putc pop until empty`.
* Other non-command substrings are literal: pushed from backward.
> 0 votes

# Answer
# Javascript, 54 bytes

```
[`MSwgMi`,`OTksIDEwMA`].map(atob).join`, miss a few, `

```

\*inspired by @arnauld 's answer
> 0 votes

# Answer
# !@#$%^&\*()\_+, 34 bytes

```
^!# ,@@^# ,wef a ssim ,(@)c# ,@@d#

```

Try it online!

Explaination:

```
^!# ,@@^# ,wef a ssim ,(@)c# ,@@d# (implicit push 0)
^                                  Top of stack += 1
 !#                                Output Top of stack as number without popping
    ,@@                            Output ", "
       ^                           Top of stack += 1
        #                          Output Top of stack as number
          ,wef a ssim ,(@)         Output ", miss a few, "
                          c#       Push 99 onto the stack and output
                             ,@@   output ", "
                                d# Push 100 onto the stack and output

```
> 0 votes

---
Tags: code-golf, kolmogorov-complexity, restricted-source
---


title: Compare Two Fractions With ASCII Art

text:
# Question
Title: Compare Two Fractions With ASCII Art
# Challenge

Write a program or function that takes in 4 non-negative integers, A, B, C, and D, that represent two fractions, A/B and C/D, where B and D are non-zero and A \<= B and C \<= D.

Output an ASCII art depiction of the fractions made of `|x-` characters on two lines as follows:

* The lines will always be the same, minimal length for the input, and both always start and end with `|`.
* The top line will depict A/B by having B sections of `-`'s separated by `|`'s with A of the sections replaced by `x`'s as if they are filling up the 1 whole of the full line.
* Likewise, the bottom line will depict C/D by having D sections of `-`'s separated by `|`'s with C of the sections replaced by `x`'s as if they are filling up the 1 whole of the full line.

It will probably make the most sense if I show an example. Suppose A/B = 2/5 and C/D = 1/3, then the output should be:

```
|xx|xx|--|--|--|
|xxxx|----|----|

```

Here the lines are the same length, as required, and the top one depicts 2 out of 5 sections filled with `x`'s while the bottom one depicts 1 out of 3 sections filled with `x`'s.

As another example, A/B = 1/2 and C/D = 5/8 would give:

```
|xxxxxxx|-------|
|x|x|x|x|x|-|-|-|

```

Notice how the number of `x`'s or `-`'s in each section between `|`'s is the same in any one line but can vary depending on the fractions and the requirement that the two lines are the same length overall.

In the first example it'd be impossible to just have 1 character between the `|`'s for 2/5

```
|x|x|-|-|-|    (2/5 with 1 character between bars)
|xx|--|--|     (invalid for 1/3 paired with 2/5 since line too short)
|xxx|---|---|  (invalid for 1/3 paired with 2/5 since line too long)

```

but with 2 characters between `|`'s it works as shown above.

**Your program must use the shortest lines possible.** This keeps them easy to read.

The cool idea here is that it's super easy to look as these ASCII art depictions of fractions and see which one is greater or if they are equal, just by how the sections line up.

So for the first A/B = 2/5 and C/D = 1/3 example, this output

```
|xxxxx|xxxxx|-----|-----|-----|
|xxxxxxxxx|---------|---------|

```

would be invalid, as, even though the lines are the same length and depict the correct fractions, they can be shorter as shown above.

# Scoring

This is a challenge so the shortest program wins!

Additional notes and rules:

* As stated, B and D will be positive, and A will be from 0 to B inclusive, and C will be from 0 to D inclusive.
* There must be at least one `x` or `-` between each pair of `|` as otherwise it's impossible to tell how much of the fraction is filled.
* The output can have a trailing newline or not, doesn't matter.
* You can take in two fractions directly instead of 4 integers if it makes sense for your language.

# Testcases

Each testcase is 3 lines, the input `A B C D` on one line, followed by the two lines of the output. Empty lines separate testcases.

```
2 5 1 3
|xx|xx|--|--|--|
|xxxx|----|----|

1 2 5 8
|xxxxxxx|-------|
|x|x|x|x|x|-|-|-|

0 1 0 1
|-|
|-|

0 1 0 2
|---|
|-|-|

1 3 1 2
|x|-|-|
|xx|--|

1 2 1 3
|xx|--|
|x|-|-|

1 2 2 4
|xxx|---|
|x|x|-|-|

1 2 2 2
|x|-|
|x|x|

3 3 1 9
|xxxxx|xxxxx|xxxxx|
|x|-|-|-|-|-|-|-|-|

3 5 4 7
|xxxxxx|xxxxxx|xxxxxx|------|------|
|xxxx|xxxx|xxxx|xxxx|----|----|----|

28 30 29 30
|x|x|x|x|x|x|x|x|x|x|x|x|x|x|x|x|x|x|x|x|x|x|x|x|x|x|x|x|-|-|
|x|x|x|x|x|x|x|x|x|x|x|x|x|x|x|x|x|x|x|x|x|x|x|x|x|x|x|x|x|-|

7 28 2 8
|x|x|x|x|x|x|x|-|-|-|-|-|-|-|-|-|-|-|-|-|-|-|-|-|-|-|-|-|
|xxxxxx|xxxxxx|------|------|------|------|------|------|

1 7 2 13
|xxxxxxxxxxxx|------------|------------|------------|------------|------------|------------|
|xxxxxx|xxxxxx|------|------|------|------|------|------|------|------|------|------|------|

1 7 2 14
|xxx|---|---|---|---|---|---|
|x|x|-|-|-|-|-|-|-|-|-|-|-|-|

0 10 0 11
|----------|----------|----------|----------|----------|----------|----------|----------|----------|----------|
|---------|---------|---------|---------|---------|---------|---------|---------|---------|---------|---------|

3 10 4 11
|xxxxxxxxxx|xxxxxxxxxx|xxxxxxxxxx|----------|----------|----------|----------|----------|----------|----------|
|xxxxxxxxx|xxxxxxxxx|xxxxxxxxx|xxxxxxxxx|---------|---------|---------|---------|---------|---------|---------|

10 10 11 11
|xxxxxxxxxx|xxxxxxxxxx|xxxxxxxxxx|xxxxxxxxxx|xxxxxxxxxx|xxxxxxxxxx|xxxxxxxxxx|xxxxxxxxxx|xxxxxxxxxx|xxxxxxxxxx|
|xxxxxxxxx|xxxxxxxxx|xxxxxxxxx|xxxxxxxxx|xxxxxxxxx|xxxxxxxxx|xxxxxxxxx|xxxxxxxxx|xxxxxxxxx|xxxxxxxxx|xxxxxxxxx|

```

# Answer
> 14 votes
# Excel (ms365), 134 bytes

Credits to @JosWooley for this is essentially his answer.

Formula in `E2`:

```
="|"&TEXTJOIN({"";"
|"},0,REPT(REPT({"x","-"},(1+(MOD(D1,B1)=0))*LCM(B1,D1)/VSTACK(B1,D1)-1)&"|",CHOOSE({1,2;3,4},A1,B1-A1,C1,D1-C1)))

```

---

**2nd Answer**: 74 + 81 = 155 bytes

Credits to @EngineerToast for this is essentially his answer.

Formula in `E2`:

```
=LET(x,2-SIGN(MOD(D1,B1)),z(A1,B1,LCM(B1,D1)*x)&"
"&z(C1,D1,LCM(B1,D1)*x))

```

Note that there should be a literal newline character pieces this together, where `z()` refers to a named function:

```
=LAMBDA(a,b,m,LET(x,m/b-1,"|"&REPT(REPT("x",x)&"|",a)&REPT(REPT("-",x)&"|",b-a)))

```

---

***Original Answer:** 118 + 138 = 256 bytes*

Formula in `E2`:

```
=z(TEXTJOIN("|",0,,IF(SEQUENCE(B1)<=A1,"x","-"),),TEXTJOIN("|",0,,IF(SEQUENCE(D1)<=C1,"x","-"),))

```

This refers to a named function called 'z':

```
=LAMBDA(a,b,LET(x,LEN(a),y,LEN(b),q,SUBSTITUTE(SUBSTITUTE(IF(x<y,a,b),"|-","|--"),"|x","|xx"),IF(x=y,a&CHAR(10)&b,IF(x<y,z(q,b),z(a,q)))))

```

The idea here is that we create two strings with single 'x' and '-' between pipe-symbols. Z is a named function that will now check the length of both strings and will replace '|x' and '|-' with '|xx' and '|--' respectively for the shortest of the two. It will do so untill the strings have the same length. When found the same length, just concat them together with a newline.

# Answer
> 11 votes
# Python, 152 bytes

Here's the program I used to generate the testcases. I'm sure someone more skilled could golf it down more (and I'd be interested to see!).

```
import math
def p(a,b,c,d):
 L=math.lcm(b,d)
 if L==max(b,d):L*=2
 def f(l,x,d):print('|'+f'{"x"*l}|'*x+f'{"-"*l}|'*d)
 f(L//b-1,a,b-a)
 f(L//d-1,c,d-c)

```

It defines the function `p` so calling `p(A, B, C, D)` produces the output.

The idea is to imagine all but the first `|` in each line as part of the `x` or `-` sections to simplify the math, and then put the `|`'s back in later.

The lcm of the denominators L is the length of the lines, not counting the first `|`. When L is equal to the larger of B or D then each section would be length 1 which would end up looking like `||||||` so the `if L==max(b,d):L*=2` line fixes that situation. Other than that trick it's mostly doing some f-string fanciness to print the lines with the correct values.

# Answer
> 8 votes
# 05AB1E, 32 bytes

```
ø`©.¿D®àQ>*®÷<„x-Sδ×'|ìsIíÆø×J€Ć

```

Port of *@blaketyro*'s Python answer, so make sure to upvote him/her as well!

Input as a pair of pairs `[[a,b],[c,d]]`, output as a pair of strings.

Try it online or verify all test cases.

**Explanation:**

```
ø              # Zip/transpose the (implicit) input-matrix, swapping rows/columns:
               #  [[a,b],[c,d]] → [[a,c],[b,d]]
 `             # Pop and push both rows separated to the stack
  ©            # Store the top pack [b,d] in variable `®` (without popping)
   .¿          # Pop and get its Least Common Multiple
     D         # Duplicate that
      ®à       # Push the maximum from pair [b,d]
        Q      # Check if it's equal to the LCM
         >     # Increase that 0 or 1 by 1
          *    # Multiply it to the LCM
           ®/  # Divide it by the values of pair `®`
             < # Decrease both by 1
  „x-          # Push string ["x-"]
     S         # Convert it to a pair ["x","-"]
        δ      # Apply double-vectorized on the two pairs:
         ×     #  Repeat the string the integer amount of times
          '|ì '# Then prepend a "|" in front of each of the four strings
  s            # Swap so the pair of numerators is at the top of the stack
   I           # Push the input-matrix again
    í          # Reverse each inner row
     Æ         # Reduce each inner list by subtracting
      ø        # Create pairs of the two top pairs
               #  [a,c] and [b-a,d-c] → [[a,b-a],[c,d-c]]
       ×       # Repeat the earlier strings that many times
J              # Join the inner pair of strings together
 €             # Map over both strings in this pair:
  Ć            #  Enclose it; appending its own head (the "|")
               # (after which the pair of strings is output implicitly as result)

```

# Answer
> 6 votes
# Vyxal `j`, ~~31 29~~ 27 bytes

```
yD∆Ŀ~cßdεȮ/‟ʁ≤‛x-i*ƛ\|j\|ø.

```

Try it Online! or Verify some test cases

-2 bytes thanks to lyxal :)

I'm aware of Vyncode but I'm probably going to stick to regular SBCS bytes in my answers for the time being.

| Code | Stack (bottom to top) |
| --- | --- |
| Implicit input | `(3 | 5 | 2 | 3)` |
| `y` Every other, and the rest | `(3 | 2) (5 | 3)` |
| `D` Push top of stack twice | `(3 | 2) (5 | 3) (5 | 3) (5 | 3)` |
| `∆Ŀ` Least Common Multiple | `(3 | 2) (5 | 3) (5 | 3) 15` |
| `~c` Execute without pop: Is A in B? | `(3 | 2) (5 | 3) (5 | 3) 15 0` |
| `ßd` If so, double, otherwise don't | `(3 | 2) (5 | 3) (5 | 3) 15` |
| `ε` Absolute difference | `(3 | 2) (5 | 3) (10 | 12)` |
| `Ȯ` Carry second-to-top over | `(3 | 2) (5 | 3) (10 | 12) (5 | 3)` |
| `/` Divide | `(3 | 2) (5 | 3) (2 | 4)` |
| Rotate stack right | `(2 | 4) (3 | 2) (5 | 3)` |
| `ʁ` Range \[0, n) | `(2 | 4) (3 | 2) ((0 | 1 | 2 | 3 | 4) | (0 | 1 | 2))` |
| Greater than or equal to? | `(2 | 4) ((0 | 0 | 0 | 1 | 1) | (0 | 0 | 1))` |
| `‛x-` String literal "x-" | `(2 | 4) ((0 | 0 | 0 | 1 | 1) | (0 | 0 | 1)) "x-"` |
| `i` Index into | `(2 | 4) (("x" | "x" | "x" | "-" | "-") | ("x" | "x" | "-"))` |
| `*` Repeat string n times | `(("xx" | "xx" | "xx" | "--" | "--") | ("xxxx" | "xxxx" | "----"))` |
| `ƛ` Map over each item: | Showing first pass through: |
| `\|j` Join by "|" | `"xx|xx|xx|--|--"` |
| `\|ø.` Enclose in "|" | `"|xx|xx|xx|--|--|"` |
| `j` flag: Join final result by newlines | Implicit output of result |

Let me know if this format of explanation is good, by the way. I'm trying to experiment with doing it in a method that is more obvious what is happening, but it does take up a lot of space.

# Answer
> 5 votes
# JavaScript (ES6), 113 bytes

```
(p,q,P,Q)=>(F=w=>(n=q*w-Q*W)?F(w+=n<0||!++W):(g=w=>n>q*w?n=`
`:'x-|'[n++%w?n>p*w|0:2]+g(w))(w)+g(W,p=P,q=Q))(W=2)

```

Try it online!

### Commented

```
( p, q,                // p / q = 1st fraction
  P, Q                 // P / Q = 2nd fraction
) => (                 //
  F = w =>             // F is a recursive function taking a first width w
                       // explicitly and a second width W implicitly
  (n = q * w - Q * W)  // let n be the difference between q * w and Q * W
                       // (NB: n is reused as a counter in the 2nd phase)
  ?                    // if n is not equal to 0:
    F(                 //   do a recursive call to F:
      w += n < 0       //     increment w if n is negative
           || !++W     //     increment W if n is positive
    )                  //   end of recursive call
  :                    // else (n = 0):
    ( g = w =>         //   g is a recursive function taking w
      n > q * w ?      //   if n is greater than q * w:
        n = `\n`       //     append a linefeed and reset n to a 0'ish value
      :                //   else:
        'x-|'[         //     append one of these characters:
          n++ % w      //       if w is not a divisor of n (which is
          ?            //       incremented afterwards):
            n > p * w  //         append '-' if n > p * w, or 'x' otherwise
            | 0        //
          :            //       else:
            2          //         append the separator '|'
        ] + g(w)       //     append the result of a recursive call
    )(w) +             //   1st call to g, using (w, p, q)
    g(W, p = P, q = Q) //   2nd call to g, using (W, P, Q)
)(W = 2)               // initial call to F with w = W = 2

```

# Answer
> 4 votes
# APL (Dyalog APL), 45 bytes

Call as `A C f B D`.

```
{'-x|'[2,⍨↑⍺(>⌈2×1,2≠/⊢)¨⌊⍵×⊂÷⍨∘⍳⍨(∧⌈2×⌈)/⍵]}

```

Attempt This Online!

Or, for the same length:

```
{'-x|'[2,⍨↑,¨2,¨(¯1+⊃(,÷⍨∧⌈2×⌈)/⍵)/¨⍪¨⍺>⍳¨⍵]}

```

Attempt This Online!

# Answer
> 4 votes
# AWK, ~~265 253 248 239~~ 230 bytes

```
function g(p,q){return q?g(q,p%q):p}function l(s,j){a=s;for(i=1;i++<M;)a=a s;b=a=j?a"|":z;for(i=1;i++<j;)b=b a;return b}L+=(L=(B=$2)*(D=$4)/g(B,D))==(B<D?D:B)?L:0,$0="|"l("x",$1,M=L/B-1)l("-",B-$1)"\n|"l("x",$3,M=L/D-1)l("-",D-$3)

```

Try it online!

* -9 bytes thanks to @ceilingcat
* -9 bytes:
    + -1 replaced `""` with `z`
    + -8 replaced last structure by implicit assignation

---

This use POSIX awk, and not gawk.
In gawk you can use the abbreviation `func` for `function`.
GAWK function :

> In many awk implementations, including gawk, the keyword function may be abbreviated func. (c.e.) However, POSIX only specifies the use of the keyword function. This actually has some practical implications. If gawk is in POSIX-compatibility mode (see Command-Line Options), then the following statement does not define a function:
>
> ```
> func foo() { a = sqrt($1) ; print a }
>
> ```

# Answer
> 3 votes
# Ruby, ~~98 94~~ 93 bytes

```
->a,b,c,d{[[a,b],[c,d]].map{|x,y|[p,*[?x*~k=b.lcm(d)/y*~1[b%d*(d%b)]]*x,*[?-*~k]*y-=x,p]*?|}}

```

Try it online!

# Answer
> 3 votes
# Julia, 77 bytes

```
n|d=(l=lcm(d...);x=l*2^(l∈d).÷d.-1;p='|';@. p*('x'^x*p)^n*('-'^x*p)^(d-n))

```

Attempt This Online!

Accepts input as two vectors: numerators `n` and denominators `d`.

# Answer
> 3 votes
# Pyth, 45 bytes

```
=GyW}J/*FKeMQiFKKJjmsm?%k/Ged?>cFdckG\x\-\|hG

```

Try it online!

Takes input as a list of lists `[[a, b], [c, d]]`.

### Explanation

First we compute the length of the lines (minus 1). This is the least common multiple of `b` and `d`, multiplied by 2 if it is exactly `b` or `d`. We save this number in the variable `G`.

```
                      # implicitly assign Q = eval(input())
         KeMQ         # assign K to [b, d]
       *FK            # multiply the elements of K
      /      iFK      # divide by the gcd of K (to obtain lcm)
     J                # assign this to J
  yW             J    # conditional apply doubling to J
    }J          K     # if J is in K
=G                    # assign this to G

```

Next, we loop through the input and `G+1` choosing the correct character for each position through two conditional operators.

```
jmsm?%k/Ged?>cFdckG\x\-\|hGQ    # implicitly add Q
 m                         Q    # map d over Q
   m                     hG     #   map k over G+1
    ?%k/Ged                     #     if (k % (G / d[-1])):
           ?>cFdckG             #       if (d[0] / d[1] > k / G):
                   \x           #         "x"
                                #       else:
                     \-         #         "-"
                                #     else:
                       \|       #       "|"
  s                             #   sum the list of chars into a string
j                               # join on newlines and print

```

# Answer
> 3 votes
# Arturo, ~~113~~ 105 bytes

```
$->a[e:lcm@[a\1a\3]if∨e=a\1e=a\3->'e*2map a[x y]->[124]++map
e'z->(0=z%e/y)?->124->(z>x*e/y)?->45->120]

```

Try it

```
$->a[                     ; a function taking a list of four integers named a
    e:lcm@[a\1a\3]        ; assign lcm of 2nd and 4th args to e
    if∨e=a\1e=a\3->       ; if e is equal to 2nd or 4th arg...
        'e*2              ; double e in place; this ensures no zero-width sections
    map a[x y]->          ; map over input in pairs, assign to x and y
        [124]++           ; prepend pipe character to...
        map e'z->         ; map over [1..e] and assign current elt to z
            (0=z%e/y)?->  ; does e/y divide z? Then...
                124       ; pipe
            ->            ; otherwise
            (z>x*e/y)?->  ; is z greater than x times e/y? Then...
                45        ; x
            ->            ; otherwise
                120       ; hyphen
]                         ; end function

```

# Answer
> 3 votes
# Java (JDK), 166 ~~172~~ bytes

> -6 bytes thanks to @KevinCruijssen !

Thank you for the challenge, it was very cool!

```
(a,b,c,d)->{var r="";int i,j=0,p=b,q=d;while(p!=q|p<=b|q<=d)p+=p<q?b:0*(q+=d);for(;j++<2;r+="|\n",b=d,a=c)for(i=0;i++<b;)r+="|"+(i>a?"-":"x").repeat(p/b-1);return r;}

```

Try it online!

---

A little explanation of my answer: first we calculate the
"**Least Common Multiple strictly greater than the `b` and `d` parameters**"
using the following: `p=b,q=d;while(p!=q|p<=b|q<=d)p+=p<q?b:0*(q+=d);`
which leaves the result in `p`.
Then we draw the 2 lines (using a small loop) with an inner loop that decides using its index wether we should draw a `x` or `-`, and we repeat this character a number of times using:
the "**greater-LCM**", divided by the `b` or `d` parameter (depending on the current line), minus 1.
And the `|` and `\n` are put where they should be during the process.

# Answer
> 2 votes
# Charcoal, 50 bytes

```
Ｎθ⊞υＮＮη⊞υＮ≔ΣυζＷΣ﹪ζυ≦⊕ζＦυ«⟦⭆⊕ζ⎇﹪κ÷ζι§-x‹κ×θ÷ζι|⟧≔ηθ

```

Try it online! Link is to verbose version of code. Explanation:

```
Ｎθ⊞υＮＮη⊞υＮ

```

Input the four integers, but push the denominators to the predefined empty list.

```
≔ΣυζＷΣ﹪ζυ≦⊕ζ

```

Calculate the adjusted LCM of the denominators, which is like the LCM execpt that it can't equal either denominator. This is achieved by starting the search with the sum of the denominators.

```
Ｆυ«

```

Loop over the denominators.

```
⟦⭆⊕ζ⎇﹪κ÷ζι§-x‹κ×θ÷ζι|⟧

```

Calculate the display for this denominator.

```
≔ηθ

```

Copy the second numerator to the first so that the second loop calculates the display for the second denominator correctly.

43 bytes by taking the inputs in the order B, D, A, C:

```
Ｆ²⊞υＮ≔ΣυζＷΣ﹪ζυ≦⊕ζＦυ«Ｎθ⟦⭆⊕ζ⎇﹪κ÷ζι§-x‹κ×θ÷ζι|

```

Try it online! Link is to verbose version of code.

# Answer
> 2 votes
# SAS, 181 (73+108) bytes

1. The code:

Macro (73):

```
%macro m(x,n,k);s=repeat("&k",&n-2);do i=1to &x;put s+(-1)"|"@;end;%mend;

```

Data step (108):

```
data;set;L=LCM(b,d);L=L+(L=b<>d)*L;put"|"@;%m(a,L/b,*)%m(b-a,L/b,-)put/"|"@;%m(c,L/d,*)%m(d-c,L/d,-)put;run;

```

*Process:*

Process assumes that input data are passed in a SAS dataset with variables `a`, `b`, `c`, and `d`. Dataset has to be created just before executing the code.

Example data (extending test cases):

```
data i;
  input A B C D;
cards;
2 5 1 3
1 2 1 3
1 2 2 4
1 2 2 2
3 3 1 9
1 3 1 9
1 3 3 9
3 9 5 15
3 5 4 7
28 30 29 30
7 28 2 8
1 7 2 13
1 7 2 14
0 10 0 11
3 10 4 11
10 10 11 11
2 3 11 17
1 10 2 10
10 100 20 100
1 10 10 100
1 10 1 1
1 1 1 10
3 3 1 9
1 1 1 1
0 1 0 1
;
run;

```
2. Human readable code:

Macro:

```
%macro m(x,n,k);
  s = repeat("&k", &n-2);

  do i = 1 to &x;
    put s +(-1) "|" @;
  end;
%mend;

```

Data step:

```
data ;
  set ;
  L = LCM(b, d);
  L = L + (L = b<>d)*L;

  /* put / / a +(-1)"/" b "  " c +(-1)"/" d; */

  put "|" @;
    %m(  a, L/b, *)
    %m(b-a, L/b, -)
  put / "|" @;
    %m(  c, L/d, *)
    %m(d-c, L/d, -)
  put ;
run;

```

Uncoment the `put / / a +(-1)"/" b " " c +(-1)"/" d;` line to have nicer looking result in the log.

# Answer
> 2 votes
# , 55 52 51 bytes

```
'-x|'{~(*.(%*1+e.),)&{:(2,~&,2,.}.@#"+)&>;&((>i.)/)

```

Try it online!

Great challenge, surprisingly difficult to golf, and tried a few different approaches just to get this:

The basic idea is:

1. First create each fraction with no dividing bars, using 0 for "empty" and 1 for "full". Eg, \\$ \frac{2}{3}\\$ is `1 1 0` and \\$\frac{1}{5}\\$ is `1 0 0 0 0`.
2. Next we compute the amount each number needs to "puff up", so that the final length is the modified LCM -- 15 in this case. The modification, described in many other answers, is to double the LCM when one of the denominators *is* the LCM.
3. "Puff up" each number as needed -- 5x for \\$ \frac{2}{3}\\$ and 3x for \\$\frac{1}{5}\\$ (extra spaces for clarity):

```
1 1 1 1 1   1 1 1 1 1   0 0 0 0 0
1 1 1  0 0 0  0 0 0  0 0 0  0 0 0

```
4. Change the first element in each group to a 2, to represent the divider, and append and extra 2 at the end:

```
2 1 1 1 1   2 1 1 1 1   2 0 0 0 0  2
2 1 1  2 0 0  2 0 0  2 0 0  2 0 0  2

```
5. Convert to ascii:

```
|xx|--|--|--|--|
|xxxx|xxxx|----|

```

# Answer
> 2 votes
# Thunno 2 `N`, 30 bytes

```
zẸÐDŀƁƇ⁺×_\µ«L©ı`x-si;×ı'|j'|ṛ

```

Requires Thunno 2.2.0+ for stack rotation. ATO is on v2.1.9.

Port of Jacob's Vyxal answer. See that answer for a more detailed explanation.

#### Explanation

```
zẸ          # Uninterleave into two pieces
  ÐD        # Quadruplicate so four copies are on the stack
    ŀ       # Pop one copy and push the LCM
     ƁƇ     # Without popping anything, check for containment
       ⁺×   # Increment and multiply (i.e. double if true)
         _  # Subtract the list from this number
\           # Divide the two lists
 µ«         # Rotate the stack left
   L        # Lowered range of each number
    ©       # Less than or equal to
     ı      # Map over this list of lists:
      `x-   #  Push the string "x-"
         s  #  Swap so the list is on top
i           #  Index into the string
 ;          # End map
  ×         # Multiply each string by each number
   ı        # Map over this list of lists:
    '|j     #  Join the list by the character "|"
       '|ṛ  #  And surround this string by the character "|"
            # N flag joins by newlines
            # Implicit output

```

#### Screenshot

# Answer
> 1 votes
# Jelly, 30 bytes

```
:g/He¡$$ṚṬ€ḷⱮ"Ʋ~R}¦"ṭ€1ị“|x-”Y

```

A full program that accepts the denominators, `[B, D]` and the numerators, `[A, C]`, and prints the result.

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

### How?

```
:g/He¡$$ṚṬ€ḷⱮ"Ʋ~R}¦"ṭ€1ị“|x-”Y - Main Link: [B, D]; [A, C]
              Ʋ                - last four links as a monad - f([B, D]):
       $                       -   last two links as a monad - f([B, D]):
      $                        -     last two links as a monad - f([B, D]):
  /                            -       reduce by:
 g                             -         greatest common divisor (GCD)
     ¡                         -       repeat...
    e                          -       ...number of times: exists in?
                                              - i.e. if the GCD is one B or D:
   H                           -       ...action: halve (the GCD)
:                              -     ([B, D]) integer divide (that) (vectorises)
        Ṛ                      -   reverse
         Ṭ€                    -   untruth each - e.g. 4 -> Patten = [0,0,0,1]
             "                 -   zip with ([B, D]) applying:
            Ɱ                  -     map (across implicit range [1..x]):
           ḷ                   -       left argument
                                   - i.e. B and D copies of the respective Patterns
                   "           - zip with ([A, C]) applying:
                  ¦            -   sparse application...
                R}             -   ...to indices: range of right -> [1..A] or [1..C]
               ~               -   ...action: bitwise NOT -> 0:-1 and 1:-2
                    ṭ€1        - tack each to a one - handles the leading "|"
                        “|x-”  - list of characters = "|x-"
                       ị       - (repeated, augmented Patterns) index into (those)
                                   - 1-based and modular so -2 & 1 are '|',
                                     0 is '-', and -1 is 'x'.
                             Y - join with a newline
                               - implicit, smashing print

```

# Answer
> 1 votes
# Perl 5 `-MList::Util=pairmap -pa`, ~~97~~ 96 bytes

```
($_,$\)=pairmap{"|x"x$a."|-"x($b-$a)."|
"}@F;($c<0?$_:$\)=~s/\|\K./$&$&/g while$c=y///c-length$\

```

Try it online!

Brute force method. Creates each fraction with only one character between the lines. Then it extends the length of the shorter by one more character between the lines, repeatedly, until the two lengths are the same.

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


title: Wrt "Hello World" prgrm bt wth n vwls

text:
# Question
Title: Wrt "Hello World" prgrm bt wth n vwls
Create A "Hello, World!" program but without any vowels. Winner is the program with the least bytes.

**Rules:**

* No vowels are allowed in the code.
* Must print to STDOUT
* Must be a full program.
* Submissions are measured in Bytes

Any language goes as long as there aren't any vowels

Edit: Y is only a vowel if there aren't any other vowels in the same word.

# Answer
> 1 votes
# Charcoal, 18 bytes

```
⍘Ｉ”)¶iτCφ(≦$χ≕G＆”γ

```

Try it online! Link is to verbose version of code. Explanation:

```
 Ｉ”...”     Cast compressed string `22011474394810164197455861` to integer
⍘      γ    Convert to base 95 using printable ASCII
            Implicitly print

```

Best I could do without compression was 19 bytes:

```
⭆Pmttw4(_wztl)℅⁻℅ι⁸

```

Try it online! Link is to verbose version of code. Explanation: Subtracts `8` from the ASCII codes of each character in the string constant. (Other values such as `2` can also be used.)

# Answer
> 1 votes
Got it, MetaGolfScript-695337743287229800148806645588258 solution is 0 bytes

# Answer
> 0 votes
# Thunno 2 / Vyxal (polyglots), 2 bytes

```
kH

```

Attempt This Online! or Try it Online!

Making this a CW because it's very boring and exactly the same as the normal Hello, World! submissions in Thunno 2 and Vyxal.

# Answer
> 0 votes
# Jelly, 10 bytes

Always remember to “;ṇTry HARD

```
“;ṇṪṙẏHȦ»Ḋ

```

A full program which prints the result (also a niladic Link yielding it).

**Try it online!**

### How?

Without the restriction, we could have the compressed string `“3ḅaė;œ»` for \\$8\\$ bytes.

```
“;ṇṪṙẏHȦ»Ḋ - Main Link: no arguments
“;ṇṪṙẏHȦ»  - compressed string = "\nHello, World!"
         Ḋ - dequeue -> "Hello, World!"
           - implicit print

```

---

#### Other \\$10\\$ byters

(...with nothing that could be considered a vowel, like `Ȧ`)

```
“¿ṃ{+ṀH“£» - Main Link: no arguments
“......“.» - list of compressed strings:
 ¿ṃ{+ṀH    -   "Hello, World"
        £  -   "!"
             -> ["Hello, World", "!"]
           - implicit, smashing print

```

TIO

```
“Ṣc çsṢƑ»Ṗ - Main Link: no arguments
“Ṣc çsṢƑ»  - compressed string = "Hello, World!$"
         Ṗ - pop -> "Hello, World!"
           - implicit print

```

TIO

# Answer
> 0 votes
# Retina, 21 bytes

```
K`H1ll3, W3rld!
T`d`v

```

Try it online! Explanation:

```
K`H1ll3, W3rld!

```

Start with the string constant `H1ll3, W3rld!`.

```
T`d`v

```

Change `1` to `e` and `3` to `o`.

# Answer
> 0 votes
# GolfScript, 19 bytes

```
'Gdkkn+Vnqkc '{)}%

```

Try it online!

```
'Gdkkn+Vnqkc '      Hello world but -1 applied to each character
               {)}%  Add back 1 to each character

```

# Answer
> 0 votes
# NASM (linux x32), 66 bytes

The source code in hexadecimal

```
64 62 22 04 04 43 E8 0E 22 2C 30 2C 30 2C 30 2C 37 32 2C 31 30 31 2C 22 6C 6C 22 2C 31 31 31 2C 22 2C 20 57 22 2C 31 31 31 2C 22 72 6C 64 21 22 2C 31 30 2C 22 5A B1 0E 87 D1 CD 80 B0 01 4B CD 80 22

```

Printed out it looks like this:

```
db"C�",0,0,0,72,101,"ll",111,", W",111,"rld!",10,"Z�K̀"

```

This basically encodes the following assembly:

```
add al, 4
inc ebx
call _f
data db "Hello, World!", 10
_f:
pop edx
mov cl, 14
xchg edx, ecx
int 0x80
mov al, 1
dec ebx
int 0x80

```

The instruction pointer is used to make the code position independent. Unfortunately `pop ecx` corresponds to the character `Y`, so I had to add an exchange.

To compile, run

```
nasm -f elf32 golf.S -o golf.o
ld -m elf_i386 -o golf.out golf.o
./golf.out

```

where `golf.S` contains the source code

# Answer
> 0 votes
# 05AB1E, 7 (or 23) bytes

```
”Ÿ™,‚ï!

```

Try it online.

If we want to get rid of vowels like `Ÿ` and `ï` as well, it would be **23 bytes** (most likely golfable some more, though..):

```
'H.•7¤p³mƶG•¦#`™„, s'!J

```

Try it online.

**Explanation:**

```
”Ÿ™,‚ï!            # Push dictionary string "Hello, World!"
                   # (which is output implicitly as result)

```

```
'H                '# Push "H"
                   #  STACK: "H"
.•7¤p³mƶG•         # Push compressed string "jello world"
                   #  STACK: "H","jello world"
          ¦        # Remove the first letter: "ello world"
                   #  STACK: "H","ello world"
           #       # Split it on spaces: ["ello","world"]
                   #  STACK: "H",["ello","world"]
            `      # Pop and push both separated to the stack
                   #  STACK: "H","ello","world"
™                  # Titlecase the top word: "World"
                   #  STACK: "H","ello","World"
„,                 # Push string ", "
                   #  STACK: "H","ello","World",", "
   s               # Swap it with "World" on the stack
                   #  STACK: "H","ello",", ","World"
'!                '# Push "!"
                   #  STACK: "H","ello",", ","World","!"
J                  # Join all strings on the stack together
                   #  STACK: "Hello, World!"
                   # (after which the result is output implicitly)

```

# Answer
> 0 votes
# Japt, 11 bytes

```
`HÁM, Wld!

```

Try it

# Answer
> 0 votes
# YASEPL, 48 bytes

```
=d#"H"$101›#"ll"+10›-67›#" W"+67›#"rld"-78›

```

i \<3 character codes

---
Tags: code-golf, restricted-source, hello-world
---


# Question
Title: Implement the `<=>` three-way comparison operator on numbers
In C++, there exists a `a <=> b` three-way comparison operator that, for numerical types, does the following:

* If `a < b`, then return a negative number.
* If `a = b`, then return a (mathematically speaking) sign-less number.
* If `a > b`, then return a positive number.

## The Challenge

Implement the **shortest** full program, function, method, or custom operator such that, when given two numbers of the same type `a` and `b`,

* If `a < b`, then return `-1`.
* If `a = b`, then return `0`.
* If `a > b`, then return `1`.

### Notes

* If you're writing in x86 assembly, this question may be of use to you.
* This is , so shortest answer in bytes wins!

# Answer
> 8 votes
# BQN, 2 bytes

```
×-

```

Try it at BQN REPL

```
×       # sign of
 -      # left arg minus right arg

```

---

# BQN, 3 bytes

```
<->

```

Try it at BQN REPL

This clearly isn't the shortest possible solution in BQN (see above), but it is particularly visually appealing due to its similarity to the C++/Perl/etc `<=>` operator.

```
<->     # 3-element train abc
        # ( x abc y expands to: (x a y) b (x c y) )
<       # left arg < right arg
 -      # minus
  >     # left arg > right arg

```

(a similar 'reverse-comparison' operator - `>-<` is also possible and also \[I think\] looks nice)

# Answer
> 8 votes
# polyglot, 3 bytes

```
<=>

```

Try it in Perl!

\<Insert other languages that already have the exact `<=>` operator here\>

# Answer
> 7 votes
# Python 2, 3 bytes

```
cmp

```

A built-in function that accepts \\$a\\$ and \\$b\\$ and returns \\$a \lt = \gt b\\$.

**Try it online!**

# Answer
> 6 votes
# JavaScript (ES6), 17 bytes

Expects `(a)(b)`.

```
a=>b=>(a>b)-(a<b)

```

Try it online!

# Answer
> 5 votes
# Python 3, 22 bytes

```
lambda a,b:(a>b)-(a<b)

```

Try it online!

Python 3 lacks the builtin `cmp`

-1 thanks to Dominic van Essen

# Answer
> 4 votes
# Vyxal, 2 bytes

Try it Online!

Takes input as b then a. Simply subtract the two numbers and get the sign of the result.

Alternatively a more fun looking, symbol only answer comes in at 17 bytes:

## Vyxal, 17 bytes

```
-:::-<[::-$~-|:]/

```

Try it Online!

Also takes b then a. This answer is purely just for fun, and could be made shorter by using numbers and letters (`-D0<[N|:]/`).

### Explained

```
-:::-<[::-$~-|:]/
-:                # Subtract the two numbers and push a copy
  ::-             # Push 0 to the stack by subtracting the top of the stack from itself
     <            # Is the original top of the stack < 0?
      [           # If so:
       ::         #   Duplicate the top of the stack twice. This could just be `D`, but that wouldn't be a symbol.
         -        #   Subtract those copies to get 0 again.
          $~-     #   Push the 0 under the top of the stack, and subtract without popping. The stack is now [0, a - b, -(a - b)]
             |    # Otherwise:
              :   #   Just duplicate the top of the stack
               ]  # this whole if statement was to make sure there was [a - b, abs(a - b)] as the stack
                / # Divide the top two stack items to get either -1, 0 or 1. negative/positive = -1, 0/0 = 0 and positive/positive = 1

```

# Answer
> 4 votes
# Java (JDK), 14 bytes

```
Float::compare

```

Try it online!

## Java (JDK), 13 bytes

```
Long::compare

```

Try it online!

Only supports integers.

# Answer
> 4 votes
# , 3 bytes

```
*@-

```

Try it online! The 3-byte solution `>-<` featured in a few other answers also works for the same byte count (greater-than minus less-than).

Works for any numeric type. Anonymous dyad.

## Explanation

```
*@-
*     sign
 @    of
  -   difference

```

# Answer
> 4 votes
# Excel, 12 bytes

```
=SIGN(A1-B1)

```

where `A1` and `B1` contain *a* and *b* respectively.

# Answer
> 4 votes
# Nibbles, 1.5 bytes (3 nibbles)

```
`$-

```

```
`$-         # full program
`$-$@       # with implicit args shown;
`$          # get sign of
   $        # arg1
  -         # minus
    @       # arg2

```

# Answer
> 4 votes
# K (ngn/k), 9 bytes

```
1&-_1^-%-

```

Try it online!

K lacks a sign builtin, which makes this a bit trickier.

`-%-` negative square root of a-b. This is negative if a\>b, zero if a=b and `-0n` (negative null value) if a\<b.
`1^` Replace null with 1.
`-_` floor and negate the number. In combination with the earlier `-` this does a ceil on the square root.
`1&` take the minimum of 1 and this number.

If the input was restricted to integers, `0 1'` would calculate the sign, leading to `0 1'-` as a full solution.

# Answer
> 4 votes
# Go, ~~52~~ 51 bytes

```
func(a,b int)int{n:=1
for-1<n&&b-a<n{n--}
return-n}

```

Attempt This Online!

By @Kevin Cruijssen. Uses a `for` loop to get the return value rather than a chain of `if`s.

### Changelog

* -1 by @naffetS

### Old answer, 56 bytes

```
func(a,b int)int{n:=0
if a>b{n=1}
if a<b{n=-1}
return n}

```

Attempt This Online!

Go doesn't have any sort of built-in `abs` like C, or default type methods like Java, so a function it is. Go also doesn't have ternary expressions, so the old-school "set and check" pattern is needed.

# Answer
> 4 votes
# Raku, 8 bytes

```
+(*cmp*)

```

Try it online!

`cmp` is Raku's built-in smart comparison operator, and `*cmp*` is an anonymous function that passes its arguments to that operator.

Unfortunately for this challenge, `cmp` doesn't return -1, 1, or 0, but one of the enumerated values `Less`, `More`, or `Same`, so the prefix `+` operator converts those values into their integer values.

The non-golfy solution would be to just compose the two operators:

```
&prefix:<+> o &[cmp]

```

# Answer
> 3 votes
## HP‑41C series,  ~~9~~  11 Bytes

`a` needs to be entered first, then `b`, so `a` is placed in the Y register and `b` in the X register.

```
01♦LBL⸆S     5 Bytes    global label requires 4 + m Bytes
02 SF 24     2 Bytes    ignore “out of range” errors, and instead
                        return ±9.999999999E99 as an approximation
03 −         1 Byte     X ≔ Y − X
04 X≠0?      1 Byte     if X = 0 then skip next line
05 SIGN      1 Byte     ↯ `SIGN` returns `1` for zero
06 RTN       1 Byte     `RTN` does not affect local label search

```

# Answer
> 3 votes
# Kotlin, 16 bytes

```
Float::compareTo

```

Try it online!

Annoyingly, longer than Java.

# Kotlin, 14 bytes

```
Int::compareTo

```

Try it online!

Works only on ints (I edited this after seeing that Java got edited).

# Answer
> 3 votes
# , 15 bytes

```
\(a,b)sign(a-b)

```

Attempt This Online!

# Answer
> 3 votes
# 05AB1E, 2 bytes

```
.S

```

Builtin. Takes the inputs in the order \\$b,a\\$.

Try it online.

**Explanation:**

```
.S  # Compare the second (implicit) input-integer `a` with the first (implicit)
    # input-integer `b`, and push -1 if a<b; 0 if a==b; or 1 if a>b
    # (which is output implicitly as result)

```

# Answer
> 3 votes
# Golfscript, 7 bytes

```
.~>\~<-

```

read from stdin

```
# explanation:
. # duplicate
~ # unpack
> # gt
\ # store the result and get duplicated stdin again
~ # unpack
< # lt
- # gt-lt

```

# Answer
> 3 votes
# Burlesque, 2 bytes

```
cm

```

Try it online!

Built in compare.

# Answer
> 3 votes
# PIC16F88x Machine Code, 6 words (84 bits)

A function that expects `a` to be at address 0x70 in memory, and `b` to be in register W. Returns the result in register W.

The PIC16 uses 14-bit instruction words. Because the number of words is even, this function can be represented exactly in hex with no padding:

```
0bc1d03d001ff0dfff401

```

In mpasm syntax, that is:

```
    SUBWF 0x70,F   ; Subtract W from the value at 0x70. Leave the result at
                   ; 0x70.
    BTFSC STATUS,2 ; Check the zero flag (bit 2 of the STATUS register) and skip
                   ; the next instruction if it's not set.
    RETLW 0x00     ; Set the W register to 0 and return.
    BTFSC 0x70,7   ; Skip the next instruction if the MSb of the value at 0x70
                   ; is 0 (i.e. the result of subtraction is positive).
    RETLW 0xFF     ; Set the W register to 0xff (-1) and return.
    RETLW 0x01     ; Set the W register to 1 and return.

```

Bit for bit, this is encoded as:

```
00 0010 1111 0000
00 0010           SUBWF
         111 0000       0x70
        1                    F

01 1101 0000 0011
01 11             BTFSC
         000 0011       STATUS
     01 0                      2

11 0100 0000 0000
11 01             RETLW
        0000 0000       0x00
     00                      (ignored)

01 1111 1111 0000
01 11             BTFSC
         111 0000       0x70
     11 1                    7

11 0111 1111 1111
11 01             RETLW
        1111 1111       0xff
     11                      (ignored)

11 0100 0000 0001
11 01             RETLW
        0000 0001       0x01
     00                      (ignored)

```

The PIC16F88x family of microcontrollers have four memory banks of 128 bytes each. (These are actually bytes this time, and not 14-bit words.) Which one is used depends on the value of the STATUS register. However, addresses 0x70 through 0x7f are the same on all banks, so by placing the operands there the function doesn't have to change banks to access them. I'm not aware of any standard calling convention as far as argument location goes, but the return value being in register W is standard (hence the existence of the `RETLW` instruction).

# Answer
> 3 votes
# K (ngn/k), 5 bytes

```
-/<?,

```

Try it online!

* `,` concatenate the inputs
* `<?` grade-up the distinct-ified result from above; if the first value is smaller than the second, the result will be `0 1`; if larger, `1 0`, if the same, `,0`
* `-/` run a minus-reduce and (implicitly) return

An alternative version that takes the input as a list of two numbers is `-/<?:`.

# Answer
> 2 votes
## Pascal, 55 Bytes

```
function f(a,b:real):real;begin f:=ord(a>b)-ord(a<b)end

```

# Answer
> 2 votes
# Retina 0.8.2, 29 bytes

```
\d+
$*
(1*) \1
0
1+0
1
01+
-1

```

Try it online! Link includes test cases. Only works on non-negative integers. Explanation:

```
\d+
$*

```

Convert to unary.

```
(1*) \1
0

```

Try to subtract; this will leave `0` if `a = b`.

```
1+0
1

```

If `a > b` then replace the result with `1`.

```
01+
-1

```

If `a < b` then replace the result with `-1`.

# Answer
> 2 votes
# Charcoal, 12 bytes

```
ＮθＮηＩ⁻›θη‹θη

```

Try it online! Link is to verbose version of code. Explanation: Port of @Arnauld's JavaScript answer.

Alternative approach, also 12 bytes:

```
≔⁻ＮＮθＩ÷θ∨↔θ¹

```

Try it online! Link is to verbose version of code. Explanation: Divides the difference between the numbers by the absolute value of the difference, or `1` if that's zero.

# Answer
> 2 votes
# MathGolf, 2 bytes

Try it online.

**Explanation:**

```
,  # Subtract the second (implicit) input by the first (implicit) input: b-a
 σ # Get the sign of that (-1 if <0; 0 if ==0; 1 if >0)
   # (after which the entire stack is output implicitly as result)

```

# Answer
> 2 votes
# C (gcc), 22 bytes

This is practically @TobySpeight's answer now since he changed the entire algorithm.

```
f(a,b){a=(a>b)-(a<b);}

```

Try it online!

# Answer
> 2 votes
# Pyth, 3 bytes

```
._-

```

Try it online!

Defines a function which takes two inputs b, a.

### Explanation

```
  -    # subtract the second argument from the first
._     # take the sign

```

# Answer
> 2 votes
# Pip, 4 bytes

```
aCMb

```

There's a built-in operator for that. (Fun fact: in my original designs for Pip, this operator was `<=>`, until I realized that having a 3-character operator in a golfing language was silly.)

Attempt This Online!

# Answer
> 2 votes
# Julia 1.0, ~~13~~ 3 bytes

```
cmp

```

Try it online!

-10 bytes thanks to MarcMush: use `cmp`

## Alternate solution, 13 bytes

```
a%b=sign(a-b)

```

Try it online!

## Alternate solution (15 bytes)

```
a%b=(a>b)-(a<b)

```

Try it online!

Some operators have lower precedence than `<` and `>`. Redefining one of them as `-` removes the need for parentheses but doesn't save bytes overall:

```
~=-
a%b=a>b~a<b

```

Try it online!

# Answer
> 2 votes
# Piet \+ ascii-piet, 21 bytes (4×7=28 codels)

```
vekabrA krbtkFbks?Tbb

```

Try Piet online!

Just a minor variation from my answer to "output the sign". Takes two numbers and subtracts instead of taking just one number, and then the rest follows the same logic.

```
A1->A4
inN inN -    [a-b] Take two numbers and subtract
A4->A7->B7->B5
dup 1 ! > !  [a-b a-b<=0]
CC+          [a-b] Continue on row B if a-b<=0, shift to row C otherwise
B5->B2
! 1 -        [(a-b==0)-1] -1 if a-b!=0 (which implies a-b<0), 0 otherwise
C5->C2
1            [a-b 1] Ignore the previous number and push 1
C2->C1
outN         Print the top number and exit

```

# Answer
> 2 votes
# AArch64 machine code, 16 bytes

AArch64's conditional select instructions get their time to shine.

```
0000000000000000 <spaceship>:
   0:   eb01001f    cmp x0, x1
   4:   9a9f07e0    cset x0, ne
   8:   da80a400    cneg x0, x0, lt
   c:   d65f03c0    ret

```

`cset` sets the destination register to 1 or 0 according to whether the condition code is true or false. (Fun fact: it's actually an alias for `csinc x0, xzr, xzr, eq`, where `csinc X, Y, Z, cond` sets X to Y if the condition is true, and to Z+1 if false.)

`cneg X, Y, cond` sets X either to -Y or Y according to whether the condition is true or false. (Alias for `csneg X, Y, Y, cond`.)

Several other permutations are also possible, such as

```
cset x0, gt              // x0 = (a > b) ? 1 : 0
csinv x0, x0, xzr, lt    // x0 = (a < b) ? x0 : ~0

```

# Answer
> 2 votes
# Lua, 45 bytes

```
load"a,b=...return a>b and 1or a<b and-1or 0"

```

Try it online!

Lua has a strict type system, and there is no shorter way than `a and 1or 0` to convert a boolean to an integer.

This version works for all comparable types (e.g. integer, floating point, and string).

# Lua, 35 bytes

```
load"a,b=...return-1+2/(0^(a-b)+1)"

```

Try it online!

This is based on my answer to Output the sign. It gives the correct result for all floating point inputs, and most integer inputs.

It doesn't meet the requirements of this challenge for integer inputs, as it will fail when passed, for example, `math.maxinteger` and `math.mininteger` (as demonstrated in the test harness), because subtracting one from the other results in an overflow. But it does fully work for all floating point inputs, thus meeting the challenge's requirements for that type.

# Answer
> 2 votes
# Haskell, ~~24~~ 23 bytes

```
a#b|a<b= -1|a>b=1|0<1=0

```

Try it online!

-1, thanks to Unrelated String!

The 'nicer' solution of `((pred.fromEnum).).compare` is 26 bytes.

# Answer
> 2 votes
# Wolfram Language (Mathematica), 5 bytes

```
Order

```

Try it online!

Input `Order[b, a]`. Works on any atomic numbers.

Note the reversed order of inputs.

# Answer
> 2 votes
# PowerShell, 19 bytes

```
[math]::Sign($a-$b)

```

Try it online!

# Answer
> 2 votes
# minigolf, 18 bytes

```
TiiT*+1+,:1+s,T+__

```

Attempt This Online! (Since minigolf is not properly added to ATO yet, I'm using a Python runner here.)

## Explanation

We use `-1` as the base of our output. If `a-b >= 0`, we increment `-1` `a-b+1` times. However, if our output reaches `2`, we decrement it back to `1`.

T                 0, Base our signum output on -1 _
iiT*+             0, a + b * -1 _
1+                0, increment the result _
,                 0, Repeat that many times: _
  :1+s            0, Increment signum but keep the original value _
                  0, This is useful because we only want to _
                  0, decrement once in the 2 case _
  ,               0, If our previous signum value is 1: do this once _
    T+            0, Add signum value by -1 _
  _               0, End foreach loop _
_                 0, End foreach loop _

0, Implicit output the signum value left on the stack _
```
</code></pre>

# Answer
> 1 votes
# Jelly, 2 bytes

```
_Ṡ

```

A dyadic Link that accepts \\$a\\$ on the left and \\$b\\$ on the right and yields \\$a \lt = \gt b\\$.

**Try it online!**

### How?

```
_Ṡ - Link: a, b
_  - (a) subtract (b)
 Ṡ - sign -> -1, 0, or 1

```

# Answer
> 1 votes
# ARBLE, ~~25~~ 15 bytes

```
lt(a,b)-gt(a,b)

```

Same as Arnauld's JS solution. Unfortunately Verbose, throwing away the advantages of the langauge.

Try it online!

# Answer
> 1 votes
# Japt, 2 bytes

```
gV

```

Try it

```
g   # sign of the difference of implicit first input and
 V  # second input

```

# Answer
> 1 votes
# Thunno, \\$ 3\log\_{256}(96)\approx\\$ 2.47 bytes

```
_za

```

Attempt This Online!

Sign of `a-b`.

# Answer
> 1 votes
# Brachylog, 2 bytes

```
-ṡ

```

Try it online!

Same answer as many other esolangs.

### Explanation

```
-     Subtract
 ṡ    Sign

```

# Answer
> 1 votes
# Ruby, 12 bytes

```
->a,b{a<=>b}

```

Try it online!

(feels like cheating)

# Answer
> 1 votes
# simply, 8 bytes

Does exactly the expected.

```
&compare

```

This is a built-in function that simply returns the expected result.

---

## Example:

### Code-like

```
// Should output 1
echo &compare(2, 1);

```

### Plain-English-like

```
// Should output -1
Show the result of calling &compare with the arguments 1, 2.

```

---

## Test code:

This shows test results in a nice pretty table.

```
// Test data - self-explanatory
// Example 5 shows an error, as an example
$tests = &json_decode(<<<JSON
[
    {"a": 0, "b": 1, "result": -1},
    {"a": 1, "b": 2, "result": -1},
    {"a": 2, "b": 1, "result": 1},
    {"a": 2, "b": 2, "result": 0},
    {"a": 3, "b": 2, "result": 0}
]
JSON);

// Make the table pretty
$settings = call !TABLE->getDefaultSettings();
$settings->classHeader = &str_concat($settings->classHeader, " table-dark");
$settings->classBodyCell = &str_concat(
    $settings->classBodyCell,
    " text-center"
);
$settings->classBodyFirstCol = &str_concat(
    $settings->classBodyFirstCol,
    " text-center table-dark"
);
$settings->classHeaderItems = &str_concat(
    $settings->classHeaderItems,
    " w-25"
);

// Create the table
$table = call !TABLE->create($settings);

call $table->setHeader(["", "A", "B", "Result"]);

each $test in $tests {
    // This is where the function runs
    $result = &compare($test['a'], $test['b']);

    call $table->addRow(
        &iff(
            $result == $test["result"],
            "✔",
            &str_concat("❌ (", $test["result"], ")")
        ),
        $test['a'],
        $test['b'],
        $result
    );
}

call $table->show();

```

### Result:

This is an example of how the table will look like.

# Answer
> 1 votes
# Desmos, 15 bytes

```
f(a,b)=sgn(a-b)

```

Try It On Desmos!

# Answer
> 1 votes
# Binary-encoded Golfical, 27 bytes

Hexdump of binary encoding:

```
00 30 07 15 14 14 14 14 17 17 0c 01 14 14 14 17
00 01 02 01 1c 15 3b 4e 23 26 1d

```

Original program image:

Magnified 40x with RGB colors labeled:

Based on my answer here.

# Answer
> 1 votes
# Common Lisp, 28 bytes

```
(lambda(a b)(signum(- a b)))

```

# Answer
> 1 votes
# MMIX machine language, 2 instrs (8 bytes)

For `s64`:

```
00000000: 30000001 f8010000                    0¡¡¢ẏ¢¡¡

```

Disassembled:

```
    CMP $0,$0,$1        // x = x <=> y
    POP 1,0             // return x

```

For `u64`:

```
00000000: 32000001 f8010000                    2¡¡¢ẏ¢¡¡

```

Disassembled, the only change is the first instruction is now `CMPU`.

For `f64`:

```
00000000: 01000001 f8010000                    ¢¡¡¢ẏ¢¡¡

```

And this time the first instruction is `FCMP`.

All of these functions are excellent candidates for inlining.

# Answer
> 1 votes
# Ly, 14 bytes

```
nns=!rlLfp2*,*

```

Try it online!

Longer than I'd hoped, but I couldn't find a shorter way to do it given the instructions available...

```
nns             - read in two numbers, stash the second one away
   =!           - are they equal? invert result so "0" is set for equal
     rl         - reverse stack, recover the second number
       L        - do "less than" comparison
        fp      - delete the first number (it's still on the stack)
          2*,   - converts "0" to "-1" and "1" stays "1"
             *  - multiple by "are they equal?" val to get "0" as needed

```

# Answer
> 1 votes
# Python, 31 Bytes

```
lambda a,b:(x:=a-b)and x/abs(x)

```

-7 Bytes from The Thonnu.

`abs(x)` gets the absolute value of `x` (think of it as scissors that can cut the `-` sign off numbers).

# Answer
> 1 votes
# PARI/GP, 3 bytes

```
cmp

```

Attempt This Online!

# Answer
> 1 votes
## Common Lisp, 24 bytes

```
(compose'floor'signum'-)

```

This is the functional composition of functions `floor`, `signum` and `-`.

The `signum` function computes the sign and return the expected values, but for floating point values the result is also a float, either `-1.0`, `-0.0`, `+0.0` or `+1.0`. That's why the `floor` operation is used to convert the result back to an integer.

# Answer
> 1 votes
# Gaia, 1 byte

```
C

```

Try it online!

# Answer
> 1 votes
# Thunno 2, 1 byte

Attempt This Online!

Built-in. Inputs in reverse order, `b` then `a`. Requires \\$\le 2.2.0\\$, as this was changed in Thunno \\$2.2.1\\$.

## Thunno 2, 2 bytes

Same as most other answers: sign of `a-b`. Inputs in normal order, `a` then `b`. Works in all versions.

Attempt This Online!

# Answer
> 0 votes
# Arturo, 7 bytes

```
compare

```

Try it

Builtin.

(In Arturo, `<=>` is the between operator. `5 <=> 1 10` would return `true`.)

# Arturo, 33 bytes

```
$[a b][(a>b)?->1->(a=b)?->0->0-1]

```

Try it

Non-builtin.

Arturo doesn't have a sign function or integer booleans, so I couldn't think of anything better than a nested ternary.

# Answer
> 0 votes
# Factor, 9 bytes

```
[ - sgn ]

```

Try it online!

Sign of difference. Factor has a `<=>` word, but it returns `+lt+`, `+eq+`, and `+gt+` symbols.

# Answer
> 0 votes
# Desmoslang Assembly, 5 Bytes

```
I-IOT

```

I belive you had said that any negative or positive number works.

# Answer
> 0 votes
# YASEPL, 40 bytes

```
=x=a'=b'!a}1,b,3}3,b}2,b,2`3!$|`2!-|`1>x

```

takes 2 inputs from STDIN.

---
Tags: code-golf, number, comparison
---


title: Is this number tetrahedral?

text:
# Question
Title: Is this number tetrahedral?
Happy New Year 2024!

2024 is a **tetrahedral number**. A tetrahedral number is a number that can be represented in the form \\$n(n+1)(n+2)/6\\$ for some positive integer \\$n\\$. Or, equivalently, they are the sum of the first \\$n\\$ triangular numbers. They are also the number of objects in a triangular pyramid which has \\$n\\$ objects on each of its edges.

For example, \\$10\\$ is a tetrahedral number because \\$10 = \frac{3 \times 4 \times 5}{6}\\$.

Here are the first few tetrahedral numbers:

```
1, 4, 10, 20, 35, 56, 84, 120, 165, 220, 286, 364, 455, 560, 680, 816, 969, 1140, 1330, 1540, 1771, 2024, ...

```

This is sequence A000292 in the OEIS.

## Task

Given a positive integer \\$n\\$, determine whether \\$n\\$ is a tetrahedral number.

This is , so the shortest code in bytes in each language wins.

This is also a , so you may use your language's convention for truthy/falsy (swapping truthy and falsy is allowed), or use two distinct, fixed values to represent true or false.

# Answer
> 11 votes
# , ~~32~~ ~~31~~ 29 bytes

```
function(n)n%in%choose(3:n,3)

```

Try it online!

Based on the observation on wiki or OEIS that \\$Te\_n={{n+2}\choose{3}}\\$; `:` ranges downwards for the case of \\$n=1\\$.

# Answer
> 8 votes
# Vyxal 3 `R`, 3 bytes

```
@@c

```

Try it Online! (link is to literate version)

Simply cumulative sum twice, and check if the input is in that.

R flag casts num to range for cumsum

# Answer
> 6 votes
# MATL, 6 bytes

```
t:tY+m

```

Try at **MATL online!**

### How it works

This uses the fact (see OEIS) that tetrahedral numbers are

> the convolution of the natural numbers with themselves

It suffices to compute the convolution of the finite sequence 1, 2, ..., *n* with itself. Also, it is not necessary to discard the "transient" (non-valid part) at the end of the convolution result, because all the values there exceed *n* and thus cannot cause false positives.

```
t     % Implicit input: n. Duplicate
:     % Range: gives [1 2 ... n]
t     % Duplicate
Y+    % Convolution
m     % Ismember. Implicit output

```

# Answer
> 6 votes
# Retina 0.8.2, 26 bytes

```
.+
$*
(^(1)|(?<2>1\2)\1)+$

```

Try it online! Link includes test cases. Explanation: The first stage just converts to unary; the second stage adds successive triangular numbers to see if this will exactly consume the unary number. The `?<2>` syntax reuses capturing group `2`; the equivalent in Perl is to use alternative capture group numbering:

# Perl 5 `-p`, 33 bytes

```
$_=(1x$_)=~/((?|^(1)|(1\2)\1))+$/

```

Try it online! Link includes test cases.

# Answer
> 5 votes
# Vyxal `R`, 23 bitsv2, 2.875 bytes

```
¦¦c

```

Try it Online!

Bitstring:

```
10110100000101111100100

```

Same as my vyxal 3 answer but with the funny haha fracbyte encoding.

# Answer
> 5 votes
# Ruby, 41 bytes

```
->n{n*=6;a=(n**3**-1).to_i;n==a*-~a*a+=2}

```

Try it online!

Finds the cube root of `n*6` rounded down,then applies the formula `a*(a+1)*(a+2)` to see if this equals `n*6`

# Answer
> 5 votes
# JavaScript (ES7), 28 bytes

*-2 thanks to @tsh*

Returns a falsy value for tetrahedral.

```
n=>(n*=6)+(n**=1/3,~n)**3-~n

```

Try it online!

### Method

Computes:

$$k=\left\lfloor (6n)^{1/3}\right\rfloor$$

And tests whether:

$$(k+1)^3-k-1=6n$$

# Answer
> 4 votes
# Jelly, 4 bytes

```
RÄÄċ

```

Try it online!

A monadic link taking an integer and returning 1 for tetrahedral and 0 for not. Similar to many of the other answers: range, cumsum, cumsum, count.

# Answer
> 3 votes
# Uiua SBCS, 10 bytes

```
∊:\+\++1⇡.

```

Try it!

Port of lyxal's Vyxal 3 answer.

```
∊:\+\++1⇡.
         .  # duplicate
        ⇡   # range
      +1    # increment
  \+\+      # cumulative sum twice
∊:          # is the input in this?

```

# Answer
> 3 votes
# Python, 42 bytes

```
lambda n:n*6in(y**3-y for y in range(n+2))

```

Attempt This Online!

Returns True/False. Saves a few bytes by shifting the closed formula by 1.

# Answer
> 3 votes
# C++, 63 57 bytes

(-6 bytes thanks to AZTECCO)

```
[](int n){for(int i=n+3;i--;)n*=n!=-~i*i*~-i/6;return n;}

```

Try it online!

This swaps truthy/falsy, so it returns an integer greater than 0 for non-tetrahedral numbers, and 0 for tetrahedral numbers.

63 byte version:

```
[](int n){for(int i=n+2;i-->0;)if(n==-~i*i*~-i/6)n=0;return n;}

```

Try it online!

# Answer
> 3 votes
# TI-BASIC, 14 bytes

```
max(Ans=cumSum(cumSum(cumSum(1 or rand(Ans

```

Takes input in `Ans`. Works on numbers that are within the list size limit.

---

### 20 bytes

```
Input N
int(³√(6N
Ans³+3Ans²+2Ans=6N

```

Based on Arnauld's answer.

# Answer
> 2 votes
# Python 3, 49 bytes

```
lambda x:any(x==n*-~n*(n+2)/6for n in range(x+1))

```

Try it online!

No extra work, just the original formula

# Python 3, 47 bytes swapping T/F

```
lambda x:all(x+n*~n*(n+2)/6for n in range(x+1))

```

Try it online!

# Answer
> 2 votes
# Desmos, 31 bytes

```
f(k)=∏_{n=1}^k(6k-nnn-3nn-2n)

```

Try It On Desmos!

Try It On Desmos! - Prettified

Returns `0` if it is a tetrahedral number, otherwise it returns a non-zero integer. For 5 more bytes, you can make it return `0` if it is a tetrahedral number, and `1` otherwise:

### 36 bytes

```
f(k)=∏_{n=1}^ksgn(6k-nnn-3nn-2n)^2

```

Try It On Desmos!

Try It On Desmos! - Prettified

# Answer
> 2 votes
# Haskell \+ hgl, 12 bytes

```
e*^xc scp<e0

```

Attempt This Online!

## Explanation

* `e0` integers from 0 to the input
* `xc scp` perform cumulative sums twice
* `e` determine if the input is an element.

## Reflection

It is infuriating I don't have a way to check for membership in an infinite monotonic list. I would have sworn I had implemented it, but I've spent a long time looking and I can't find it.

It wouldn't save bytes here, in fact if it were 3 bytes it would make this longer by a byte, but it should exist because it will be useful in the future.

# Answer
> 2 votes
# Perl 5 `-p`, 44 bytes

```
$i++while($;=$i*($i+1)*($i+2)/6)<$_;$_=$_==$

```

Try it online!

# Answer
> 2 votes
# Haskell, 32 bytes

```
f n=elem(6*n)[k^3-k|k<-[1..n+1]]

```

Try it online!

Check whether \\$6n\\$ is of the form \\$k^3-k\\$.

**32 bytes**

```
q=scanl1(+)
f n=elem n$q$q[1..n]

```

Try it online!

Using the cumulative-sum-twice method from other answers.

# Answer
> 2 votes
# Mathematica, ~~34~~ ~~33~~ 32 bytes

Outputs truthy/falsy reversed.

```
k^3-k-6#/.k->⌊(6#)^(1/3)⌋+1&

```

Try this online!

# Answer
> 1 votes
# APL(Dyalog Unicode), ~~10 9~~8 bytes SBCS

```
⊢∊+\⍣2⍤⍳

```

Try it on APLgolf!

-1 byte thanks to att.

A tacit function which takes an integer on the right and returns 1 if tetrahedral and 0 if not. Same method as the Vyxal and Uiua answers.

```
⊢∊+\⍣2⍤⍳
      ⍤⍳  # range, then
  +\      # cumulative sums,
    ⍣2    # twice
⊢∊        # input is member

```

Created with the help of Luminespire.

# Answer
> 1 votes
# Scala 3, 41 bytes

```
x=>(0 to x).exists(n=>x==n*(n+1)*(n+2)/6)

```

Attempt This Online!

# Answer
> 1 votes
# Charcoal, 20 bytes

```
ＮθＷ‹↨υ¹θ⊞υ⁺Ｌυ↨υ⁰⁼Συθ

```

Try it online! Link is to verbose version of code. Outputs a Charcoal boolean, i.e. `-` for tetrahedral, nothing if not. Explanation:

```
Ｎθ

```

Input `n`.

```
Ｗ‹↨υ¹θ

```

Until the sum reaches `n`, ...

```
⊞υ⁺Ｌυ↨υ⁰

```

... push successive triangular numbers to the predefined empty list.

```
⁼Συθ

```

See whether `n` was reached exactly.

# Answer
> 1 votes
# Python, ~~80 64 55 51 47~~ 45 bytes

```
lambda x:x*6in[k*~k*~-~k for k in range(x+1)]

```

Attempt This Online!

Based off of Aiden Chow's Desmos answer.

# Answer
> 1 votes
# Go, ~~80~~ 75 bytes

```
func(x int)int{for i:=1;i<=x;i++{if 6*x==i*(i+1)*(i+2){return 1}}
return 0}

```

Attempt This Online!

Loops over all numbers from \\$1\\$ to \\$x\\$ inclusive and sees if \\$6x = i(i+1)(i+2)\\$.

-5 from Joao-3 by using `int` as the return type instead.

# Answer
> 1 votes
# x86 32-bit machine code, 11 bytes

```
99 31 C9 01 CA 41 29 D0 77 F9 C3

```

Try it online!

Following the `regparm(1)` calling convention, this function takes a number in EAX and returns a number in EAX, which uses reversed truthy/falsy – it is 0 for tetrahedral numbers and nonzero otherwise.

In assembly:

```
f:  cdq             # Set EDX to 0 by sign-extending EAX.
    xor ecx, ecx    # Set ECX to 0.
r:  add edx, ecx    # Add ECX to EDX. EDX will run through the triangular numbers.
    inc ecx         # Add 1 to ECX.
    sub eax, edx    # Subtract EDX from EAX.
    ja r            # Jump back, to repeat, if EAX remains positive.
    ret             # Return.

```

# Answer
> 1 votes
# Raku, 48 bytes

```
->\a{^∞ .map(->\n{(n**3-n)/6}).first(*>=a)-a};

```

Attempt This Online!

Generate the sequence itself until it reaches a value greater than or equal to the input. Then return the difference, i.e., return 0 if it hits the input, and a positive integer otherwise; True/False is therefore swapped.

# Answer
> 1 votes
# 05AB1E, 7 bytes

```
LηOηOIå

```

Try it online or verify the first 100 test cases.

**Explanation:**

Similar as other answers.

```
L        # Push a list in the range [1, (implicit) input]
 ηOηO    # Cumulative sum twice:
 η       #  Get the prefixes of this list
  O      #  Sum each prefix
   ηO    #  And again
     Iå  # Check if the input is in this list
         # (which is output implicitly as result)

```

# Answer
> 1 votes
# PowerShell, 76 bytes

```
$a=$b=1;while($b-ge1){$b=$_*6/$a/($a+1)/($a+2);if($b-eq1){return !0};$a++}!1

```

Try it online!

# Answer
> 1 votes
# APL(NARS), 64 chars

```
r←B w;y;z
y←⌈3√w←w×6⋄r←0⋄→3
y-←1
→2×⍳w<z←y×(y+1)×y+2
→0×⍳w>z⋄r←1

```

9+17+4+19+11+4=64

`f(y)=y×(y+1)×(y+2)=y^3+3y^2+2y` is a crescent function and from `y0=⌈(6w)^(1/3) => (y0)^3≥6w =>(y0)^3+3(y0)^2+2(y0)>6w` so it is possible begin the loop in that point `y0` and decrease `y0` until `(y0)^3+3(y0)^2+2(y0)≤6w`

```
     a⊂⍨B¨a←⍳123
 1  4  10  20  35  56  84  120

```

it seems is possible to use big rational and big float too

```
      B 45487864677774111x
0
      B 45487864677774111x×(45487864677774111x+1)×(45487864677774111x+2)÷6
1

```

# Answer
> 1 votes
# dc, 50 bytes

```
[1pq]st[0pq]sf[1+dd1+d1+**6/dln=tln<flxx]sx?sn0lxx

```

Try it online!

This solution outputs 1 for truthy, and 0 for falsy.

# Answer
> 1 votes
# Rattle, ~~27~~ 26 bytes

```
|r`[=#-s+2*~*#/6[\=1q]]3`=

```

Try it Online!

Outputs 1 if the number is tetrahedral, 0 otherwise.

# Explanation

```
|                    take input
 r`                  set input to "\" (variable)
   [ ... ]3`         loop int("3"+str(N)) times where N is the input. The 3 catches the edge case of 1.

=#                   set the top of the stack to i, where i is the loop count
  -                  decrement
   s                 save to memory
    +2               increment by 2
      *~             multiply by the value in memory (performing (i-1)(i+1))
        *#           multiply by i to obtain (i-1)(i)(i+1), effectively the same
                          as n(n+1)(n+2) but with shifted indices
          /6         divide by 6
            [\...]   if equal to "\" (the original input)
              =1     set the top of the stack to 1
                q    quit and implicitly print the top of the stack
=                    if the loop exits without quitting, the number is not tetrahedral
                         (set top of stack to 0 then print implicitly)

```

There may be a way to get this shorter. I might come back later to try to get the byte count down (someone else should try too!).

# Answer
> 0 votes
# YASEPL, 58 bytes

```
!d'(=a`3!c$a+!b$a*c!c+!b*c/6}3,d,2!}1,d+|3`2>"Y"|4`1>"N"`4

```

requires input from stdin (it prompts you) and outputs a Y or N whether the number is tetrahedral or not

---
Tags: code-golf, number, decision-problem
---