# Question
Title: Code close to the challenge: Sum of integers
This is a simple challenge: Given a sequence of integers, find the sum of all integers in it.

But with a twist. Your score is the Levenshtein distance between your code and the following phrase (The challenge):

> Given a set of integers, find the sum of all integers in it.

You may assume there are no newlines or trailing spaces in the input.

**Example input/output:**

```
Input: 1 5 -6 2 4 5
Output: 11
Input: 1 -2 10
Output: 9

```

An online calculator for Levenshtein distance can be found here: http://planetcalc.com/1721/

# Answer
## Python, distance 3

```
#Given a set of integers, find the
sum#of all integers in it.

```

This gives the built-in function `sum`, which can sum a set like `sum({3,5,7})==17`. The remaining parts are commented. This has distance 3, with 3 edits:

* Add the initial `#`
* Add a newline
* Replace the space after `sum` with `#`
> 59 votes

# Answer
# Julia, distance ~~27~~ 26

No comments!

```
Given(a)=(Set;of;integer; find; [sum(a),all,integer,in][1])

```

This creates a function called `Given` that accepts an array and returns the sum of its elements. Since a lot of Julia builtins have relevant names (but are irrelevant to the calculation here), we can just list a few delimited with semicolons. As long as they aren't the last thing listed, they won't be returned. The last part actually makes an array containing the sum and three functions and selects the first element, the sum.
> 55 votes

# Answer
# APL, distance ~~6~~ 3

Saved 3 distances...? thanks to Dennis!

```
+/⍝en a set of integers, find the sum of all integers in it.

```

This sums a given array (`+/`). The remainder of the sentence is added to the end using a comment ().
> 22 votes

# Answer
# R, Distance ~~37~~ ~~36~~ 34

Without using comments :)

```
 as.integer ( sum (scan(,integer( ) )))

```

**Note** there is a space at the beginning.
> 10 votes

# Answer
# GolfScript, 5

```
~{Given a set of integers+ find the sum of all integers in it}*

```

This a full program that uses no comments (but a lot of noops).

Try it online in Web GolfScript.
> 10 votes

# Answer
## Mathematica, distance 17

```
Given a set of integers find the sum of all integers in it*0+Total@Input[]

```

It doesn't use any comments or no-ops, but instead declares all of the words as variables, and then gets rid of them by multiplying by zero.

It also has the benefit of being the only answer that actually takes a **set** of integers as its input.

The input `{1,2,3}` provides the output `6` as expected.

Unfortunately, the Mathematica `Sum` function doesn't do the task in the question, therefore necessitating a larger number of bytes.
> 8 votes

# Answer
# RProgN, Distance 2.

```
Given aset of integers, ;find the sum of all integers in it.

```

In RProgN, a, set, find and sum are all commands. Everything else is per default ignored in syntax. a pushes the alphabet to the stack, which will cause sum to fail. Set never has enough arguments, so always fails, erroring. Find either has the wrong number of arguments, or tries to compare the alphabet with the input stack, which doesn't work.

a and set can both be 'fixed' by removing the space between then, aset is not a function, so it's ignored. Find just has an extra character inserted at the start, causing it also to not be recognized, and ignored. Only sum is left, which conveniently sums the contents of the input stack.

Finally, RProgN might win something!

Try it Online!
> 8 votes

# Answer
# Java - ~~43~~ 41

I tried.

```
float a_set_of(int[] r){return IntStream.of(r).sum()}//n it.
Given a set of integers, find the sum of all integers in it.

```

Java :P.
> 6 votes

# Answer
# CJam, ~~7~~ ~~6~~ 5

```
{:+}e# a set of integers, find the sum of all integers in it.

```

This is an anonymous function that pops an array from the stack and leaves an integer in return.

*Thanks to @AboveFire for shortening the distance by 1.*

Try it online.
> 4 votes

# Answer
## Matlab, distance ~~29~~ 28

```
Given_a_set_of_integers=@(findthe)sum(all(1)*findthe)

```

Without using any comments :-)

The code is in the form of an anonymous function. I'm assuming the input is a vector (1D-array) of numbers.

Example:

```
>> Given_a_set_of_integers=@(findthe)sum(all(1)*findthe)
Given_a_set_of_integers =
    @(findthe)sum(all(1)*findthe)

>> Given_a_set_of_integers([1 5 -6 2 4 5])
ans =
    11

```
> 4 votes

# Answer
## F#, distance 21

```
let ``Given a set of integers, find the sum of all integers in it`` x = Seq.sum x

```

Gotta love the ability to use double ticks to give a function a name with spaces in it.

Usage:

```
[1;2;3] |> ``Given a set of integers, find the sum of all integers in it`` |> printfn "%i"

```

> 6
> 4 votes

# Answer
# Cubix, Distance 9

```
@ivOn a ;et I+ i?tegers, fu;d <he sum of all integers in it.

```

Try it online!

This wraps onto the cube

```
      @ i v
      O n a
      ; e t
I + i ? t e g e r s , f
u ; d < h e s u m o f a
l l i n t e g e r s i n
      i t .
      . . .
      . . .

```

The operative code is

* `I+i` Input a integer,add to TOS then input a character
* `?` Test character value. Redirect left for -1 (end of input) or right for anything else (0 can't be input)
    + `;O@` pop TOS, output sum and exit
    + `<;u` redirect, pop TOS and u-turn onto the start
> 4 votes

# Answer
# Vyxal 3, distance 1

```
Given a set of integersṠ, find the sum of all integers in it.

```

Try it Online!

Prints a singleton number.

## Explanation

```
Given a set of integersṠ, find the sum of all integers in it.
G                                                              ## Get the max element
 i                                                             ## index
  ve                                                           ## Is odd? (decrement, Is even?)
    n                                                          ## Push "abcdefghijklmnopqrstuvwxyz" anyway
      a                                                        ## Is the alphabet truthy? (Always)
        s                                                      ## Split! I don't know how can you split a bool with 1...
         e                                                     ## Is this even?
          t                                                    ## Get the last element (How can you do it with a bool?)
            o                                                  ## Overlap (How??)
             f                                                 ## Flatten (Already Flattened??)
               i                                               ## Index with input again
                n                                              ## Also, push "abcdefghijklmnopqrstuvwxyz" anyway
                 t                                             ## Get the last element ("z")
                  e                                            ## Split on newlines ("z" has no newlines, so pop and push ["z"])
                   g                                           ## Never gonna <g>ive you up. (I don't understand what this does anyway)
                    e                                          ## Split on newlines (Again? This time, it doesn't wrap)
                     r                                         ## replace this with input?
                      s                                        ## split with itself?
                       Ṡ                                       ## SUM!
                        ,                                      ## PRINT!
                          find the sum of all integers in it.  ## I give up. This doesn't do anything.

```

Created with the help of Luminespire.
> 4 votes

# Answer
# K, ~~60~~ 5

```
+/ / Given a set of integers, find the sum of all integers in it.

```

~~I'm guessing symbols do NOT go nicely with the Leve-whatever distance...~~

Hahaha. Originally, I had *no* what the LeveXXX distance was, so I got 60. Then, thanks to helpful comments, it dropped to 5.
> 3 votes

# Answer
# , 5

```
M]+o"Given a set of integers, find the sum of all integers in it.
```

Numbers must be in hexadecimal and in reverse negative notation:

* -6 =\> 6\_
* -4 =\> 4\_
* -10 =\> A\_

Try it online
> 3 votes

# Answer
# Pip, distance 3

Joining the club of trivial no-comments-but-lots-of-no-ops golflang answers...

```
Given a set of integers, find the sum of all integers in $+g

```

GitHub repository for Pip

The code practically documents itself; maybe `s/in/using/` for a more accurate description. Integers given as command-line arguments are read into the list `g`, which is here folded on addition and the result auto-printed. Most everything else is just variables, which are no-ops.

I was a bit surprised at first that `s, f` worked without complaining, since `f` refers to the main function and taking the range of a code block doesn't make sense. But then I realized: the `,` range operator, when given a function argument, just constructs another function (as do many operators in Pip). So I think `s, f` evaluates to `{Given a set of integers, find the sum of all integers in " ",$+g}`. (Which is then discarded anyway.)

One final point: this code works with the current version of Pip, in which I haven't assigned `G` to anything yet. If in some future version I make `G` a binary or ternary operator, then a distance-4 version would be necessary. Using `given` instead of `Given` would work nicely.
> 3 votes

# Answer
# Haskell, distance 11

No comments!

```
const sum"Given a set of integers, find the sum of all integers in it."

```

Usage:

```
> const sum"Given a set of integers, find the sum of all integers in it." $ [1..10]
55

```
> 3 votes

# Answer
# Pyth - 4

Just puts the actual code, `sQ` in front of the string no-oped by a space.

```
sQ "Given a set of integers, find the sum of all integers in it.

```

Try it online here.
> 2 votes

# Answer
# PHP4.1, distance 25

This one is a pretty long one and really late in the run.

But anyway, here it is:

```
<?=$n_a_set_of_integers_fi=array_sum($f_all_integers_in_i);

```

For this to work, you just need to pass it an array over POST/GET/COOKIE/session, using the key `f_all_integers_in_i`.
> 1 votes

# Answer
# Pyt, distance 1

```
Given a set of integers, find the Ʃum of all integers in it.

```

All alphanumeric characters are no-ops in Pyt, and the sum of a list only takes one character: Ʃ

Try it online!
> 1 votes

# Answer
# C++17, distance ~~44~~ 29

Variadic Generic Lambda FTW

```
[](auto...t){return(t+...);}//the sum of all integers in it.

```

Previous solution

```
template<class...t>int s(t...l){return(...+l);}//gers in it.

```
> 0 votes

# Answer
# 05AB1E, distance 3

```
#O,Given a set of integers, find the sum of all integers in it.

```

Try it online!
> 0 votes

# Answer
# Pyke, Score 3

```
sK"Given a set of integers, find the sum of all integers in it.

```

Try it here!
> 0 votes

# Answer
# Ly, score 4

```
&+#Given a set of integers, find the sum of all integers in it.

```

Note the trailing newline.

Try it online!

The code is pretty self-explanatory. `&+` is Ly's summing operator, while `#` is a comment. It's unfortunate that I have to include a trailing newline due to the fact that ending a program with a comment line will "comment out" Ly's implicit output, which is actually a bug in the interpreter that I'm calling a feature.
> 0 votes

# Answer
# dc, 14

```
?[+z1 <f]d  sf xp#egers, find the sum of all integers in it.

```

comments:

```
?                   # read numbers
 [                  # start macro
  +                 # add up last two things on stack
   z1 <f            # if stack size is more than 1, execute macro at register 'f'
        ]           # end macro
         d          # dupe it
            sf      # saving one copy to register 'f'
               x    # and executing another
                p   # printing result

```

TIO

it complains about the stack being empty if you enter 1 number, but still works, and removal of 0 saves 2 diff.
> 0 votes

# Answer
# Excel VBA, Distance: 11

Anonymous VBE immediate window function that takes input from the range `[a:a]` on the ActiveSheet object and outputs to the VBE immediate window

```
?[Sum(a:a)] 'f integers, find the sum of all integers in it.

```
> 0 votes

# Answer
# Brain-Flak, 20

```
(([]){[{}]{}([])}{})ers, find the sum of all integers in it.

```

Try it online!

# Explanation

Since there are no parentheses in the original text this boils down to a problem in Brain-Flak. But that still doesn't make this answer trivial, as answers in Brain-Flak rarely are.

One's first intuition would probably be the following code

```
({{}})

```

Which works ... *unless* there is a zero on the stack in which case it just sums until the zero. To get around this problem we have to use a stack height to check that the stack is not empty. This can be set up like this

```
([])    #{ Push stack height }
(       #{ Start Push }
{       #{ Loop until zero }
 <{}>   #{ Silently Pop the last height }
 {}     #{ Grab a value from the stack }
 <([])> #{ Silently push the stack height again }
}       #{ End loop }
{}      #{ Remove last stack height }
)       #{ Push the result }

```

This one works, but there is something wrong with it. We keep silencing the pops and the pushes in the loops but they are almost equal so there should be a way to cancel them out. If we try

```
([])({[{}]{}([])}{})

```

We end up off by `n` each time. So here's the trick, we already have an `n` siting around, we just move it into the push to balance things out.

```
(([]){[{}]{}([])}{})

```
> 0 votes

# Answer
# Ahead, 17

```
>jLIve>   K+O @f integers, find the sum of all integers in it.
^ >j<l

```

Try it online!
> 0 votes

# Answer
# Jelly, Distance: 2

```
Given a set of integers, find the sum of all integers in it.
S

```

Try it online!

Jelly only evaluates the main link (the last line) and explicit commands will run other links (other lines).

The last line has `S`, which sums the input.

The first line does not get executed because there is no reference to it in the main link.
> 0 votes

# Answer
# Snap! 4.2.2.9 (+ Tools), scratchblocks3 syntax, distance 35

This is a function. `integers, find the sum of all inte` is the input.

```
for each(et)of(integers, find the sum of all inte
change[s v]by(et
end
report(s

```
> 0 votes

# Answer
# 05AB1E, distance 2

```
O,Given a set of integers, find the sum of all integers in it.

```

Try it online!

```
O,...  # trimmed program
 ,     # output...
O      # sum of...
       # implicit input...
 ,     # explicitly to prevent the fatal error from stopping implicit output
  ...  # no-op as implicit output has been canceled by the print command and the rest of the code doesn't contain any more print commands

```

In case you're curious, the error occurs because of `G`, and because the item on top of the stack is a list. `G` is a loop, looping the variable `N` through the list `[1, 2, 3, ..., top of stack - 1]`. Since `,` pops the item on top of the stack before printing, `G` has no arguments to use and instead uses implicit input. Since you can't subtract a number from a list, it errors.

Alternatively, replacing the second character (`,`) with one of these, combined with optionally removing the `G`, will also work:

```
?  # erroring solution - with G
=  # non-erroring solution - with G
,  # non-erroring solution - without G
?  # non-erroring solution - without G
=  # non-erroring solution - without G
D  # non-erroring solution - without G

```
> 0 votes

# Answer
# AWK, distance 15

```
 i+=$ a set of integers{ find the sum of all inte}END{print i}

```

Attempt This Online!

Takes numbers separated by newlines from stdin, and prints the sum.

AWK allows referencing undefined variables. They default to 0 in numeric context and `""` (empty string) in string context. AWK also has string concatenation `x y`, which makes large part of the code valid no-ops.

The sum is stored in `i` because `int i}` and `in it.` has distance 1 lower than using any other variable, but it ends up with 1 higher distance somewhere else...
> 0 votes

# Answer
# Uiua, distance 3

```
/+#en a set of integers, find the sum of all integers in it.

```

Test pad (the formatter sucks)
> 0 votes

# Answer
# Go, score 48, 63 bytes

```
func( a...int) int {e:=0;for _,h:=range  a{     e+=r};return e}

```

Attempt This Online!
> 0 votes

---
Tags: code-challenge, source-layout
---


title: Display numbers lacking 2's

text:
# Question
Title: Display numbers lacking 2's
Display numbers from one to one-hundred (in increasing order), but number 2 shouldn’t appear anywhere in the sequence. So, for example, the numbers two (`2`) or twenty-three (`23`) shouldn't be in the sequence.

Here is an example output, with newlines separating the numbers:

```
1
3
4
5
6
7
8
9
10
11
13
14
15
16
17
18
19
30
31
33
34
35
36
37
38
39
40
41
43
44
45
46
47
48
49
50
51
53
54
55
56
57
58
59
60
61
63
64
65
66
67
68
69
70
71
73
74
75
76
77
78
79
80
81
83
84
85
86
87
88
89
90
91
93
94
95
96
97
98
99
100

```

# Answer
> 13 votes
# 05AB1E, 6 bytes

```
тLʒ2å_

```

Try it online!

**Explanation**

```
тL       # push [1 ... 100]
  ʒ      # filter, keep only elements that
   2å_   # does not contain 2

```

# Answer
> 26 votes
# Taxi, ~~2399~~ ~~2391~~ ~~2370~~ ~~1783~~ ~~1773~~ 1706 bytes

*-8 bytes for realizing that, instead of leaving a certain passenger at Sunny Side Park forever, it's more worth it to throw them off of Riverview Bridge. Ah, what a lovely town this is.*

*-21 bytes for taking out a comment I stupidly left in.*

*-587 bytes by simply changing the entire way I went about this (apparently a shorter way is by arithmetic; integer-dividing \[17, 27, 37, 47,...\] by 9 yields the sequence, but you gotta skip over the 20's yourself.)*

*-17 bytes for the realization that any quotes-encased string without a space doesn't need quotes after all (thanks Jo King!).*

*-67 bytes for the realization that linebreaks are optional.*

```
17 is waiting at Starchild Numerology.Go to Starchild Numerology:w 1 l 2 r 1 l 1 l 2 l.Pickup a passenger going to Cyclone.Go to Cyclone:e 1 l 2 r.[B]Pickup a passenger going to Cyclone.Pickup a passenger going to Divide and Conquer.9 is waiting at Starchild Numerology.Go to Starchild Numerology:s 2 l 2 r.Pickup a passenger going to Divide and Conquer.Go to Divide and Conquer:e 1 l 2 r 3 r 2 r 1 r.Pickup a passenger going to Trunkers.Go to Trunkers:e 1 r 3 r 1 l.Pickup a passenger going to The Babelfishery.Go to The Babelfishery:e 1 r 1 r.Pickup a passenger going to Post Office.\n is waiting at Writer's Depot.Go to Writer's Depot:n 5 l 2 l.Pickup a passenger going to Post Office.Go to Post Office:n 1 r 2 r 1 l.Go to Cyclone:s 1 r 1 l 2 r.Pickup a passenger going to Addition Alley.Pickup a passenger going to Equal's Corner.177 is waiting at Starchild Numerology.Go to Starchild Numerology:s 2 l 2 r.Pickup a passenger going to Equal's Corner.Go to Equal's Corner:w 1 l.Switch to plan C if no one is waiting.Pickup a passenger going to Sunny Skies Park.100 is waiting at Starchild Numerology.Switch to plan D.[C]10 is waiting at Starchild Numerology.[D]Go to Starchild Numerology:n 1 r.Pickup a passenger going to Addition Alley.Go to Sunny Skies Park:w 1 r.Go to Addition Alley:n 1 r 1 r 1 r.Pickup a passenger going to Cyclone.Go to Cyclone:n 1 l 1 l.Pickup a passenger going to Cyclone.Pickup a passenger going to Equal's Corner.917 is waiting at Starchild Numerology.Go to Starchild Numerology:s 2 l 2 r.Pickup a passenger going to Equal's Corner.Go to Equal's Corner:w 1 l.Switch to plan E if no one is waiting.Switch to plan F.[E]Go to Go More:n 1 l.Go to Cyclone:w 1 r.Switch to plan B.[F]

```

Try it online!

This one isn't winning me any code golf competitions anytime soon, but I decided to try out the esolang Taxi.

Taxi is an esolang in which all programming is done by picking up and dropping off passengers at various stops in the fictional town of Townsburg. Of course, your taxicab will sometimes run out of gas, so you also need to visit gas stations every so often, and pay using the credits you receive as fare (in this case, I only need to stop for gas - at Go More - once per loop iteration!).

I used some tricks that reduce the filesize a bit, such as rephrasing directions like `east 1st left, 2nd right` as `e 1 l 2 r`, removing the word `the` where it is optional, and using the least complicated route towards all of my destinations (not necessarily the shortest path).

I hate this shorter solution more than the one I originally came up with. This solution down here is a more general way of accomplishing the task, which could start and end anywhere you want. Here it is, in its entirety.

# 2245 bytes (way more general)

```
1 is waiting at Starchild Numerology.Go to Starchild Numerology:w 1 l 2 r 1 l 1 l 2 l.Pickup a passenger going to Cyclone.Go to Cyclone:e 1 l 2 r.[B]Pickup a passenger going to Addition Alley.Pickup a passenger going to The Babelfishery.Go to The Babelfishery:n 2 r 2 r.Pickup a passenger going to Cyclone.Go to Cyclone:n 5 l 2 l.Pickup a passenger going to Chop Suey.Go to Zoom Zoom:n.0 is waiting at Writer's Depot.Go to Writer's Depot:w.Pickup a passenger going to Narrow Path Park.Go to Narrow Path Park:n 3 r 1 l 1 r.Go to Chop Suey:e 1 r 1 l 1 r.[C]Switch to plan E if no one is waiting.Pickup a passenger going to Crime Lab.2 is waiting at Writer's Depot.Go to Writer's Depot:n 1 l 3 l.Pickup a passenger going to Crime Lab.Go to Crime Lab:n 3 r 2 r.Switch to plan D if no one is waiting.Pickup a passenger going to KonKat's.Go to Narrow Path Park:n 5 l.Pickup a passenger going to KonKat's.Go to KonKat's:e 1 r.Pickup a passenger going to Narrow Path Park.Go to Narrow Path Park:n 2 l.Go to Chop Suey:e 1 r 1 l 1 r.Switch to plan C.[D]Go to Chop Suey:n 5 r 1 l.Switch to plan C.[E]Go to Narrow Path Park:n 1 l 1 r 1 l.Pickup a passenger going to Crime Lab.0 is waiting at Writer's Depot.Go to Writer's Depot:w 1 l 1 r 2 l.1 is waiting at Starchild Numerology.Pickup a passenger going to Crime Lab.Go to Crime Lab:n 3 r 2 r.Switch to plan F if no one is waiting.Pickup a passenger going to Riverview Bridge.Go to Cyclone:n 4 l 2 l.Pickup a passenger going to Post Office.Go to Riverview Bridge:n 2 r.\n is waiting at Writer's Depot.Go to Writer's Depot:w 2 l.Pickup a passenger going to Post Office.Go to Post Office:n 1 r 2 r 1 l.Go to Starchild Numerology:s 1 r 1 l 1 l 2 l.Switch to plan G.[F]Go to Cyclone:s 1 r 1 l 2 r.Pickup a passenger going to Riverview Bridge.Go to Riverview Bridge:n 2 r.Go to Starchild Numerology:w 2 l 3 l 2 r.[G]Pickup a passenger going to Addition Alley.Go to Addition Alley:e 1 l 2 r 3 r 1 r.Pickup a passenger going to Magic Eight.101 is waiting at Starchild Numerology.Go to Starchild Numerology:n 1 l 1 l 3 l 2 r.Pickup a passenger going to Magic Eight.Go to Magic Eight:w 1 r 2 r 1 r.Switch to plan H if no one is waiting.Pickup a passenger going to Cyclone.Go to Cyclone:n 1 l 2 r.Switch to plan B.[H]

```

Try it online!

And if mega-cheating is allowed, this one is way shorter than either of the last two.

# 456 bytes (totally cheating)

```
1\n3\n4\n5\n6\n7\n8\n9\n10\n11\n13\n14\n15\n16\n17\n18\n19\n30\n31\n33\n34\n35\n36\n37\n38\n39\n40\n41\n43\n44\n45\n46\n47\n48\n49\n50\n51\n53\n54\n55\n56\n57\n58\n59\n60\n61\n63\n64\n65\n66\n67\n68\n69\n70\n71\n73\n74\n75\n76\n77\n78\n79\n80\n81\n83\n84\n85\n86\n87\n88\n89\n90\n91\n93\n94\n95\n96\n97\n98\n99\n100 is waiting at Writer's Depot.Go to Writer's Depot:w 1 l 2 r 1 l 2 l.Pickup a passenger going to Post Office.Go to Post Office:n 1 r 2 r 1 l.

```

Try it online!

# Answer
> 24 votes
# Python 2, 39 bytes

```
k=7
exec"k+=10;print(k>177)*10+k/9;"*81

```

Try it online!

Uses arithmetic operations only to generate numbers without 2's.

The value `k` follows the arithmetic progression `17, 27, 37, 47, ...`, which when floor-divided by 9 gives `1,3,4,5,6,7,8,9,10,11,13,14,...` which counts up numbers not ending in 2. To skip 20 through 29, outputs are increased by 10 past a certain threshold.

# Answer
> 14 votes
# JavaScript (ES6), 43 bytes

Returns the sequence as a comma-separated string.

```
f=(n=98)=>n?f(n-=n-27?n%10?1:2:11)+[,n+3]:1

```

Try it online!

### Why doing it this way?

We could iterate from \\$1\\$ to \\$100\\$ and test each number with `/2/.test(n)`, which is a rather concise statement. But in this scenario, we'd have to handle empty entries with something like `(/2/.test(n)?'':...)`, which adds a couple more bytes.

For example, this would work for 45 bytes:

```
f=(n=1)=>n>99?n:(/2/.test(n)?'':[n,,])+f(n+1)

```

Or this would work for 44 bytes, if a leading comma is acceptable:

```
f=(n=100)=>n?f(n-1)+(/2/.test(n)?'':[,n]):''

```

All in all (and until proven otherwise), it turns out to be shorter to *skip right away* all values of \\$n\\$ that contain a \\$2\\$.

### Commented

```
f =                 // f is a recursive function taking:
(n = 98) =>         // n = counter, initialized to 98
  n ?               // if n is not equal to 0:
    f(              //   prepend the result of a recursive call:
      n -=          //     update n:
        n - 27 ?    //       if n is not equal to 27:
          n % 10 ?  //         if n is not a multiple of 10:
            1       //           subtract 1 from n
          :         //         else:
            2       //           subtract 2 from n
        :           //       else (n = 27):
          11        //         subtract 11 from n (--> 16)
    ) +             //   end of recursive call
    [, n + 3]       //   append a comma, followed by n + 3; notice that this is the value
                    //   of n *after* it was updated for the recursive call; at the first
                    //   iteration, we have: n = 98 -> updated to 97 -> n + 3 = 100
  :                 // else (n = 0):
    1               //   output the first term '1' and stop recursion

```

# Answer
> 12 votes
# , 19 bytes

```
grep(2,1:100,inv=T)

```

Try it online!

# Answer
> 10 votes
# Python 2, 44 bytes

```
print[n for n in range(1,101)if'2'not in`n`]

```

Try it online!

# Answer
> 10 votes
# Perl 6, 22 bytes

```
put grep {!/2/},1..100

```

Try it online!

There's probably a better way to do the code block, but I couldn't find a regex adverb to invert the match

# Answer
> 7 votes
# PowerShell, ~~22~~ 16 bytes

```
1..100-notmatch2

```

Try it online!

*-6 bytes thanks to mazzy*

Generates the range `1` to `100`, then pulls out those objects where they do `-notmatch` the number `2`. Running the `-notmatch` against an array like this acts like a filter on the array. Each item is left on the pipeline, and output is implicit.

# Answer
> 6 votes
# Japt, 7 bytes

```
Lõs kø2

```

---

```
Lõs kø2     Full Program
Lõs         Range ["1"..."100"] (numbers are casted to string)
    k       Remove
     ø2     anything that contains "2"

```

Try it online!

# Answer
> 6 votes
# Haskell, ~~48~~ ~~33~~ 31 bytes

Thanks @JonathanFrech for fifteen bytes saved, and @xnor for another two! I missed a big golf and didn't realize `main=print$` can be omitted.

```
filter(all(/='2').show)[1..100]

```

Try it online!

Easily extended by changing the `100`. Stringifies all the numbers and keeps only those without a `'2'`.

# Answer
> 6 votes
# Bash \+ GNU utilities, 16

* 1 byte saved thanks to @Dennis.

```
seq 100|sed /2/d

```

Try it online!

# Answer
> 5 votes
# Retina, ~~19~~ 17 bytes

```

100*
.
$.>`¶
A`2

```

Try it online! Edit: Saved 2 bytes thanks to @ovs, although the last line now includes a newline. Explanation:

```

100*

```

Insert 100 characters.

```
.
$.>`¶

```

Replace each character with the number of characters up to and including that character, plus a newline.

```
A`2

```

Remove all entries that contain a `2`.

# Answer
> 5 votes
# Java 10, 67 bytes

```
v->{for(int i=0;++i<101;)if(i%10!=2&i/10!=2)System.out.println(i);}

```

Try it online.

**Explanation:**

```
v->{                           // Method with empty unused parameter and no return-type
  for(int i=0;++i<101;)        //  Loop `i` in the range (0, 101)
    if(i%10!=2                 //   If `i` modulo-10 is not 2
       &i/10!=2)               //   And `i` integer-divided by 10 is not 2 either
      System.out.println(i);}  //    Print `i` with a trailing newline

```

# Answer
> 5 votes
# Powershell, 19 bytes

```
1..100-split'.*2.*'

```

This script show null-value instead 'numbers with 2 inside' and completely solves the task 'number 2 shouldn’t appear anywhere in the sequence'.

Output:

```
1

3
4
5
6
7
8
9
10
11

13
14
15
16
17
18
19

30
31

33
34
35
36
37
38
39
40
41

43
44
45
46
47
48
49
50
51

53
54
55
56
57
58
59
60
61

63
64
65
66
67
68
69
70
71

73
74
75
76
77
78
79
80
81

83
84
85
86
87
88
89
90
91

93
94
95
96
97
98
99
100

```

## Powerhsell (output does not contain null-values), 24 bytes

```
1..100-split'.*2.*'-ne''

```

# Answer
> 4 votes
# Tcl, 44 bytes

```
time {if ![regexp 2 [incr i]] {puts $i}} 100

```

Try it online!

---

~~Tcl, 47 bytes
```
time {if [incr i]%10!=2&$i/10!=2 {puts $i}} 100

```
Try it online!
~~

##

~~Tcl, 50 bytes
```
time {if {2 ni [split [incr i] ""]} {puts $i}} 100

```
Try it online!
~~

# Answer
> 4 votes
# Stax, 6 bytes

```
Ç░τ╒╜h

```

Run and debug it

Unpacked, ungolfed, and commented, it looks like this.

```
AJ  10 squared
f   output each value in [1 .. n] satisfying the following filter
 E  get array of decimal digits in number
 2#     count the number of 2s
 !  logical not

```

Run this one

# Answer
> 4 votes
# Wolfram Language (Mathematica), 42 bytes

```
Print@⌈Range[1,100,10/9]~Drop~{18,26}⌉

```

Try it online!

The arithmetic sequence 1, 19/9, 29/9, 39/9, ... grows at just the right rate that taking the ceiling skips all the numbers ending in 2. Then we get rid of 20 through 29 by `Drop`ping the values at indices 18 through 26.

# Answer
> 4 votes
## C (GCC), 62 55 Bytes

*• 7 Bytes thanks to Jonathan Frech*

`f(n){for(n=0;++n-101;n/10-2&&n%10-2&&printf("%d,",n));}`

Loops from 1 to 100 and prints the number only if 2 is not in the ones or tens place.

Try it online!

# Answer
> 4 votes
# Python 3, ~~53 51 50 49~~ 46 bytes

```
['2'in str(n)or print(n)for n in range(1,101)]

```

Try it online!

Not the strongest language for this task, but I'm new to golfing.

Thanks to the commenters for their tips!

# Answer
> 4 votes
# sh + coreutils, 16 chars

```
seq 100|sed /2/d

```

Generates sequence from 1 to 100 (inclusive) and deletes any lines that have '2' in them.

# Answer
> 4 votes
# Z80Golf, ~~49~~ 48 bytes

```
00000000: 1630 2e0a 5faf f57b fe02 2818 82ff f182  .0.._..{..(.....
00000010: ff92 3cf5 7dff f1bd 280a fe02 2803 f518  ..<.}...(...(...
00000020: e63c 18fa 7b3c bd20 db3e 31ff 3dff ff76  .<..{<. .>1.=..v

```

Try it online!

Assembly:

```
ld d, 30h			; ascii '0' character
ld l, 0Ah			; number 10 and ascii newline
tens:
	ld e,a			; store tens digit
	xor a			; reset ones digit to 0
	push af			; store initial ones digit 0
	ones:
		ld a,e		; get stored tens digit
		cp 2
		jr z,cont	; if tens digit==2(e.g.20-29),skip loop
		add d
		rst 38h 	; print tens digit
		pop af		; get stored ones digit
		add d
		rst 38h 	; print ones digit
		sub d
		inc a		; increment ones digit
		push af		; store ones digit
		ld a, l
		rst 38h 	; print newline
		pop af		; get stored ones digit again
		cp l
		jr z,cont	; if ones digit==10, break loop
		cp 2
		jr z,inc_again	; if ones digit==2, incr again
		repeat_loop:
		push af		; store ones digit again
		jr ones		; repeat print loop
		inc_again:
			inc a
			jr repeat_loop

	cont:
	ld a,e			; get stored tens digit
	inc a			; increment tens digit
	cp l
	jr nz, tens		; if tens place!=10, continue loop
ld a,31h
rst 38h				; print '1'
dec a
rst 38h				; print '0'
rst 38h				; print '0'
halt

```

Saved one byte with the `repeat_loop` jump

# Answer
> 3 votes
# Kotlin, 32 bytes

```
{(1..100).filter{'2' !in ""+it}}

```

Try it online!

# Answer
> 3 votes
# Bash, 31 bytes

```
printf %d\\n {1..100}|grep -v 2

```

Try it online!

Thanks to Digital Trauma for short loop.

# Answer
> 3 votes
# ORK, 1092 bytes

```
There is such a thing as a t
A t can w a number
A t can d a number
A t has a t which is a number

When a t is to w a number:
I have a mathematician called M
M's first operand is the number
M's second operand is 1
M is to add
The number is M's result
My t is 0
I have a number called n
n is the number
I am to d n
M's first operand is my t
M's second operand is 1
M is to compare
I have a scribe called W
If M says it's less then W is to write the number
If M says it's less then W is to write " "
M's first operand is the number
M's second operand is 100
M is to compare
If M says it's less then I am to loop

When a t is to d a number:
I have a mathematician called M
M's first operand is the number
M's second operand is 10
M is to modulo
I have a mathematician called N
N's first operand is M's result
N's second operand is 2
N is to compare
If N says it's equal then my t is 1
M is to divide
The number is M's result
M's first operand is the number
M's second operand is 0
M is to compare
If M says it's greater then I am to loop

When this program starts:
I have a t called T
T is to w 0

```

Try it online!

**O**bjects **R** **K**ool. Output is a space-delimited list of numbers.

This translates (approximately) to the following pseudocode:

```
class t {
	int t;

	void w(number) {
		label T_W;
		mathematician M;
		M.first_operand = number;
		M.second_operand = 1;
		M.add();
		number = M.result;
		t = 0;
		int n = number;
		d(n);
		M.first_operand = t;
		M.second_operand = 1;
		M.compare();
		scribe W;
		if M.its_less { W.write(number); }
		if M.its_less { W.write(" "); }
		M.first_operand = number;
		M.second_operand = 100;
		M.compare();
		if M.its_less { goto T_W; }
	}

	void d(number) {
		label T_D;
		mathematician M;
		M.first_operand = number;
		M.second_operand = 10;
		M.modulo();
		mathematician N;
		N.first_operand = M.result;
		N.second_operand = 2;
		N.compare();
		if N.its_equal { t = 1; }
		M.divide();
		number = M.result;
		M.first_operand = number;
		M.second_operand = 0;
		M.compare();
		if M.its_greater { goto T_D; }
	}
}

void main() {
	t T;
	T.w(0);
}

```

As you can see, *everything* is done using objects, including basic math and IO functions (through the built-in mathematician and scribe classes). Only whole functions can loop, which explains the need for an object with two functions to do the work.

# Answer
> 3 votes
# PHP 7.1, 40 bytes

```
while($i++<100)strstr($i,50)||print$i._;

```

prints numbers separated by underscores. Run with `-nr` or try it online.

# Answer
> 3 votes
# MathGolf, ~~7~~ 6 bytes

```
♀╒Ç{2╧

```

Try it online!

## Explanation

```
♀╒       Push 100 and convert to 1-based range ([1,2,...,100])
  Č{     Inverse filter by block
    2╧   Does the number contain 2?

```

# Answer
> 3 votes
# C (clang), 56 bytes

```
f(i){for(i=0;i++<100;i%10^2&&i/10^2&&printf("%d\n",i));}

```

Try it online!

# Answer
> 2 votes
# Red, 44 bytes

```
repeat n 100[unless find form n"2"[print n]]

```

Try it online!

Uses `unless` instead of `if not`, because why not? :)

# Answer
> 2 votes
# Ruby, 35 31 bytes

```
100.times{|e|p e if/2/!~e.to_s}

```

Try it online!

Thanks to Conor O'Brien for -4 bytes

# Answer
> 2 votes
# brainfuck, 176 bytes

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

```

Try it online!

Shorter is definitely possible. This generates the numbers `1,3,4,5,6,7,8,9` and `0,1,3,4,5,6,7,8,9`. First it outputs each number in the first list, then it outputs every combination of the first and second list, then finally prints just `100`.

### Explanation:

```
---------   Push minus 9
[           Repeat 9 times
  [-<]-[>]    Add the negative of the number to the first list
  >[>]-[-<]<  Add the negative of the number to the second list
  ++          Increment the counter
]
Tape: 255 254 253 252 251 250 249 248 247 0' 0 246 247 248 249 250 251 252 253 254
-[>-<+++++++++]>--  Push 197
Tape: 255 254 253 252 251 250 249 248 247 0 197' 246 247 248 249 250 251 252 253 254
[
  >[->]<    Subtract 197 from every element in both lists to convert to digits
  [<<<]>>
  [->]>-
]
Tape: 58 57 56 55 54 53 52 51 49 0' 49 50 51 52 53 54 55 56 57
<<,<-[-<]>[>]<  Remove the 0 and the 2 from the first list
Tape: 58 57 56 55 54 53 52 51 0 0 0' 49 50 51 52 53 54 55 56 57
[  Loop over the first list
  .[->+<]        Print digit
  ++++++++++.,<  Print a newline
]
>>[>]>>->-   Remove the 2 from the second list
<<<<
[  Loop over first list
  >>>
  [  Loop over second list
    <<[<]<.        Print first digit
    >>[>]>.        Print second digit
    [-<+>]         Move second digit over one
    ++++++++++.,>  Print a newline
  ]
  <<[<]<,<  Remove the digit from the first list and move to the next
]
>>>>.<..  Print 100 using the second list

```

# Answer
> 2 votes
# SimpleTemplate, 51 bytes

This was a fun challenge! And it is a challenge where my language can do well.

```
{@forfrom 1to100}{@if_ is notmatches"<2>"}{@echol_}

```

Cycles through all values from 1 to 100, outputting the ones that don't have 2, separated by a newline.

You can try it on http://sandbox.onlinephpfunctions.com/code/2c97a2b6954c29844f1079938da771d51e2e0d99

**Ungolfed:**

```
{@for i from 1 to 100}
    {@if i is not matches "<2>"}
        {@echo i, "\n"}
    {@/}
{@/}

```

The `{@/}` is used to close the `{@for ...}` and `{@if ...}`, but is optional.
When compiling to PHP, it adds the needed closing.

---

If you're curious, the golfed code results in this PHP code:

```
// {@forfrom 1to100}
// ~ optimization enabled ~ inlining the results
foreach(array(...) as $DATA['_']){

    // {@if_ is notmatches"<2>"}
    if(!(preg_match("<2>", (isset($DATA['_'])?$DATA['_']:null)))) {

        // {@echol_}
        echo implode('', $FN['array_flat']((isset($DATA['_'])?$DATA['_']:null)));echo PHP_EOL;

// AUTO-CLOSE
};};

```

Where `$FN['array_flat']` is defined outside of this code.

# Answer
> 2 votes
# K4, 15 bytes

**Solution:**

```
1_&~"2"in'$!101

```

**Example:**

```
q)k)1_&~"2"in'$!101
1 3 4 5 6 7 8 9 10 11 13 14 15 16 17 18 19 30 31 33 34 35 36 37 38 39 40 41 43 44 45 46 47 48 49 50 51 53 54 55 56 57 58 59 60 61 63 64 65 66 67 68 69 70 71 73 74 75 76 77 78 79 80 81 83 84 85 86 87 88 89 90 91 93 94 95 96 97 98 99 100

```

**Explanation:**

```
1_&~"2"in'$!101 / the solution
           !101 / range 0..100
          $     / string
    "2"in'      / is "2" in each?
   ~            / not
  &             / indices where true
1_              / drop the first

```

**Extra:**

TIO for **16 byte** K (oK) answer: Try it online!

# Answer
> 2 votes
# Jelly, 7 bytes

```
³D2eṆƲƇ

```

Try it online!

# Answer
> 2 votes
# Pyth, 17 bytes

```
VS100I!}\2%"%s"NN

```

Try it online

My first code golf submission, also my first time using Pyth, this took way longer to put together than I expected.

# Explanation

`VS100` **for** loop from 1 to 100

`I!}\2%"%s` **if** the string "2" is in the string conversion of N

`%"%sN` **convert N to a string.** This is the only way I could figure out how to do this. If there is a shorter way to do int -\> string conversion please let me know. I'm honestly just looking for a way to call str() or repr() on it with less chars.

`N` **print n**

EDIT: Looks like someone else beat me to it with Pyth. Turns out to convert N to a str I could do \`N\`, I'm going to leave mine the same because if I change it its almost the exact same solution.

# Answer
> 2 votes
# Scala, ~~56~~ ~~48~~ ~~47~~ ~~45~~ 42 bytes

```
1 to'd'filter(_+""forall(50!=))map println

```

Prints the elements separated by a line.

Here is a 38 bytes version that calls `toString` (technically allowed by the rules):

```
print(1 to'd'filter(_+""forall(50!=)))

```

Resulting in:

```
Vector(1, 3, 4, ..., 100)

```

# Answer
> 2 votes
# Perl 5, 19 bytes

```
map{/2/||say}1..100

```

Try it online!

# Answer
> 2 votes
# Awk, 32 bytes

```
END{while(i++<100)print i~2?a:i}

```

Try it online!

To save space, I used Awk's behavior of assigning the null string to uninitialized variables to avoid initializing the counter and saving a byte with the null string literal.

# Answer
> 2 votes
# Uiua, 36 bytes

Returns an array with numbers from 1 to 100 where the elements containing a two are removed.

```
▽×∩(≠2)⌊⊃÷◿10.+1⇡100

```

Try It

```
▽×∩(≠2)⌊⊃÷◿10.+1⇡100
              +1⇡100 # generate numbers 1..100
             . # duplicate the array for filtering
        ⊃÷◿10 # both divide by 10 and mod 10 each number
       ⌊ # floor the division result so that we have the 10s place
  ∩(≠2) # for both the mod and floored division (ones and tens places)
        # check that there is no 2
 × # use multiply as and
▽ # filter the array

```

# Answer
> 1 votes
# Pip `-l`, ~~9~~ 8 bytes

```
2N_FN\,h

```

Attempt This Online!

### Explanation

```
       h  Preset variable: 100
     \,   1-based range: [1 2 3 ... 100]
   FN     Filter Negated on this function (i.e. keep falsey results):
2N_        Number of 2s iN the argument
          Print the resulting list (newline-separated thanks to -l flag)

```

# Answer
> 1 votes
# JavaScript (ES6), 51 bytes

After reading Arnauld's answer, I wanted to try a non-recursive approach. Sure enough, it's longer, but it may be of some interest.

```
_=>[...Array(101).keys()].filter(n=>n*!/2/.test(n))

```

Try it online!

`[...Array(101).keys()]` creates a list of the numbers 0 through 100. We then `filter` to get rid of 0 and any number that contains a 2.

# Answer
> 1 votes
# Whitespace, 121 bytes

```
[S S S N
_Push_0][N
S S N
_Create_Label_LOOP][S S S T N
_Push_1][T  S S S _Add][S N
S _Duplicate][S S S T   T   S S T   S T N
_Push_101][T    S S T   _Subtract][N
T   S S N
_If_0_Jump_to_Label_EXIT][S N
S _Duplicate][S S S T   S T S N
_Push_10][T S T T   _Modulo][S S S T    S N
_Push_2][T  S S T   _Subtract][N
T   S N
_If_0_Jump_to_Label_LOOP][S N
S _Duplicate][S S S T   S T S N
_Push_10][T S T S _Integer_divide][S S S T  S N
_Push_2][T  S S T   _Subtract][N
T   S N
_If_0_Jump_to_Label_LOOP][S N
S _Duplicate][T N
S T _Print_integer_to_STDOUT][S S S T   S T S N
_Push_10][T N
S S _Print_character_to_STDOUT][N
S N
N
_Jump_to_Label_LOOP]

```

Letters `S` (space), `T` (tab), and `N` (new-line) added as highlighting only.
`[..._some_action]` added as explanation only.

Try it online (with raw spaces, tabs and new-lines only).

**Pseudo-code:**

```
Integer i = 0
Label LOOP:
  i = i+1
  If(i == 101):
    Exit program
  If(i modulo-10 == 2):
    Go to next iteration of LOOP
  If(i integer-divided by 10 == 2):
    Go to next iteration of LOOP
  Print i to STDOUT
  Print a newline to STDOUT
  Go to next iteration of LOOP

```

# Answer
> 1 votes
# APL(NARS), 17 chars, 34 bytes

```
a/⍨∼'2'∊¨⍕¨a←⍳100

```

test

```
  a/⍨∼'2'∊¨⍕¨a←⍳100
1 3 4 5 6 7 8 9 10 11 13 14 15 16 17 18 19 30 31 33
  34 35 36 37 38 39 40 41 43 44 45 46 47 48 49 50
  51 53 54 55 56 57 58 59 60 61 63 64 65 66 67 68
  69 70 71 73 74 75 76 77 78 79 80 81 83 84 85 86
  87 88 89 90 91 93 94 95 96 97 98 99 100

```

# Answer
> 1 votes
# Gol\>\<\>, 19 bytes

```
`dFLP:aSD2=$2=+ZN|;

```

Try it online!

Explanation:

```
`dFLP:aSD2=$2=+ZN|;

`d                  //Push 100 to the stack
  F                 //For loop from 0 to 99
   LP               //  Push the loopcounter+1 to the stack,achieving a range [1..100]
     :              //  Double for potential output later (saves 1 byte compared to pushing it again)
      aSD           //  Push division & modulus of current number by 10
         2=         //  Check if (num % 10) == 2 , pushes either 0 or 1
           $2=      //  Check if (num / 10) == 2 , "
              +     //  Add the results acting as a logical or for is zero question
               ZN   //  If neither the mod nor the div are equal to 2 output the number
                 |; //Exit after loop

```

# Answer
> 1 votes
# Ruby, 28 characters

```
puts [*?1..'100'].grep_v /2/

```

Thanks to:

Sample run:

```
bash-4.4$ ruby -e 'puts [*?1.."100"].grep_v /2/' | head -15
1
3
4
5
6
7
8
9
10
11
13
14
15
16
17

```

Try it online!

# Answer
> 1 votes
# , ~~14~~ 13 bytes

*Saved 1 byte thanks to @oktupol*

```
á199ñÄj<C-a>ñç2/d

```

Try it online! `<C-A>` represents the start of heading character (`0x01`)

## Explanation

```
á1            Insert a 1 on the first line
99ñ           Repeat 99 times:
 Ä             Duplicate the last line
 j<C-A>        Increment the last line by one
ñç2/          For every line containing a 2:
 d             Remove the line

```

# Answer
> 1 votes
# Forth (gforth), 58 bytes

```
: f 101 1 do i 10 /mod 2 <> swap 2 <> * if i . then loop ;

```

Try it online!

### Explanation

Loops from 1 to 100 (inclusive) and if both the ones and tens place of the index are not equal to 2, print it

### Code explanation

```
: f                    \ start a new word definition
  101 1 do             \ start a loop from 1 to 100 inclusive
    i 10 /mod          \ get the quotient and remainder of dividing i by 10
    2 <>               \ check if the the tens place is not equal to 2
    swap               \ move the result down the stack one
    2 <>               \ check that the ones place is not equal to 2
    *                  \ multiply results (cheaper AND)
    if i . then        \ if true, output i
  loop                 \ end counted loop
;                      \ end word definition

```

# Answer
> 1 votes
# Pyth, ~~13~~ 11 bytes

```
f!}`2`TS100

```

Try it online!

-2 with many thanks (nearly a year later!) to @ar4093

Original version:

```
VS*TTI!}\2`NN

```

Try it online!

I'm still a Pyth beginner so this could probably be improved on.

**Explanation**

```
for N in num_to_range(Psorted(times(T,T))):   # For N in range 1 to 10*10
 if Pnot(Pin("2",repr(N))):                   # If "2" is not in `N`
  imp_print(N)                                # Print N

```

# Answer
> 1 votes
# MBASIC, 59 bytes

```
1 FOR I=1 TO 100:IF INSTR(STR$(I),"2")=0 THEN PRINT I
2 NEXT

```

There's probably a mathematical way to do this, but this approach is what first came to mind.

# Answer
> 1 votes
# T-SQL, 65 bytes

```
DECLARE @ INT=1a:IF @ NOT LIKE'%2%'PRINT @;SET @+=1IF @<101GOTO a

```

I'm a bit annoyed that this variable loop is shorter than the best set-based SQL variant I could find (**91 bytes**):

```
SELECT DISTINCT number FROM spt_values WHERE number>0and number<101AND number NOT LIKE'%2%'

```

This one even has the additional restriction of needing to be run in the `master` database (since it uses an undocumented system table).

The best set-based solution I could find without that requirement was **94 bytes**:

```
WITH t AS(SELECT 1n UNION ALL SELECT n+1FROM t WHERE n<100)SELECT*FROM t WHERE n NOT LIKE'%2%'

```

# Answer
> 1 votes
# Perl 5 (5.12+), 25 bytes

```
$,=$/;say grep!/2/,1..100

```

Try it online!

Pretty straightforward. The `$,=$/` makes the following print put a newline between list elements, which is shorter than using `join`.

# Answer
> 1 votes
# Attache, 24 bytes

```
Output!2&`!in@List\1:100

```

Try it online!

Alternatively, `Print=>2&`!in@List\1:100`.

Filters (`\`) from `1:100` values whose digits (`@List`) do not contain (``!in`) a 2 (`2&`), which is then `Output`ted.

# Answer
> 1 votes
# Ruby, 31 bytes

```
p$.if"#{$.+=1}"!~/2/ until$.>99

```

Try it online!

A different, iterative approach than other ruby answers. This uses the not-match operator `!~` as well as the implicitly-zero input line number variable `$.` as the iterator. The TIO link shows my golfing progress, from 48 bytes to 31 bytes.

# Answer
> 1 votes
# F#, 66 bytes

## Solution

```
Seq.filter(fun i->i%10<>2&&i/10<>2){1..100}|>Seq.iter(printfn"%d")

```

## Explanation

Filters a sequence of numbers 1 to 100 by retaining those whose modulus of 10 is not 2, and which integer-divided by 10 do not result in 2, then prints the sequence with newlines between items.

This works for numbers up to and including 199. A more general solution is slightly longer (74 bytes):

```
Seq.filter(fun i->(string i).IndexOf '2'<0){1..100}|>Seq.iter(printfn"%d")

```

With proper spacing, and rearranged for readability, this looks as follows:

```
{1 .. 100}
|> Seq.filter (fun i -> (string i).IndexOf '2' < 0)
|> Seq.iter (printfn "%d")

```

# Answer
> 1 votes
# \[C# (.NET Core)\], ~~63~~ 62 bytes

Thanks to milk for saving one byte in the for loop.

```
for(int i=0;++i<101;)if(i%10!=2&&i/10!=2)Console.WriteLine(i);

```

Try it online!

Ungolfed:

```
for (int i = 0; ++i < 101;)         // all integers from 1-100 (starts from zero, increments before code runs)
    if (i % 10 != 2                 // all numbers not ending with '2'
                    && i / 10 != 2) // all numbers not starting with '2'
        Console.WriteLine(i);       // write to console

```

# Answer
> 1 votes
# Rust, 65 bytes

```
fn main(){for i in 1..101{if i%10!=2&&i/10!=2{println!("{}",i)}}}

```

Try it online!

Similar to the answers by Meerkat and dumetrulo, just iterate through and print only those whose ones digit and tens digit are not 2.

# Answer
> 1 votes
# Ohm v2, 7 9 bytes

```
⁸#u⁇2εX

```

Explanation:

```
⁸#u⁇2εX
⁸        Push 100
 #       Push range 0..a
  u      Turn to string (vectorizes)
   ⁇     Filter only those that match conditional
    2εX  Match those that do not contain "2"

```

Try it online!

# Answer
> 1 votes
# LUA, 113 68 47 45 bytes

Thanks to LUA's rather loose dynamic typing, can straight-up search the integer.

Thanks to *@manatwork* (twice)

Thanks to *@Jo King*

```
for x=1,100 do n=("").find(x,2)or print(x)end

```

Try it online!

# Answer
> 1 votes
# Crystal, 65 bytes

```
(1..100).each do |x|
    x.to_s().includes?('2') ? 0 : puts x
end

```

Try it online!

# Answer
> 1 votes
# Tidy, 27 bytes

```
{{x:"2"!in x.0}from[1,100]}

```

Try it online!

Function which returns the appropriate range. `x.0` concatenates `x` and `0` as a string.

# Answer
> 1 votes
# JavaScript (Node.js), 45 44 bytes

-1 byte thanks to Neil

```
for(i=0;i++<100;)/2/.test(i)||console.log(i)

```

Try it online!

# Answer
> 1 votes
# Windows Batch, ~~49~~ 48 bytes

```
@for /l %%G in (1,1,100)do @echo %%G|find /v "2"

```

Loops from 1 to 100, and for each number looped, only output those who does not contain any "2".

1 byte is saved by @Neil.

# Answer
> 1 votes
# Haskell, 57 Bytes

**Solution**

```
import Data.List
unlines.nub.map(filter(/='2').show).$[1..100]

```

or

```
import Data.List
nub.map(filter(/='2').show)$[1..100]

```

if you just want the list.

**Output**

```
Prelude Data.List> unlines.nub.map(filter(/='2').show)$[1..]
"1\n\n3\n4\n5\n6\n7\n8\n9\n10\n11\n13\n14\n15\n16\n17\n18\n19\n0\n30\n31\n33\n34\n35\n36\n37\n38\n39\n40\n41\n43\n44\n45\n46\n47\n48\n49\n50\n51\n53\n54\n55\n56\n57\n58\n59\n60\n61\n63\n64\n65\n66\n67\n68\n69\n70\n71\n73\n74\n75\n76\n77\n78\n79\n80\n81\n83\n84\n85\n86\n87\n88\n89\n90\n91\n93\n94\n95\n96\n97\n98\n99\n100

```

**Explanation**

Makes all numbers a string, removes their '2's and weeds out the duplicates.

# Answer
> 1 votes
# Ruby, 33 bytes

### Solution:

```
puts (?1..'100').reject{|x|x[?2]}

```

# Answer
> 1 votes
## JavaScript, 57 bytes

```
_=>`${[...Array(101).keys()]}`.replace(/^0,|\d?2.?,/g,'')

```

Try it online!

# Answer
> 1 votes
# Vyxal, 5 bytes

```
₁'2c¬

```

Try it Online!

### Explained

```
₁'2c¬
₁     # push 100 to stack
 '    # filter lambda
  2c  # contains 2
    ¬ # logical NOT

```

# Answer
> 1 votes
# Fig, \\$9\log\_{256}(96)\approx\\$ 7.408 bytes

```
Fa@2'r-2f

```

Try it online!

-1 or something thanks to Seggan

```
F         # Filter
 a@2      # range(1, 100)
    '     # by...
      -2  # Subtracting 2 from
        f # each digit
     r    # Are all truthy?

```

# Answer
> 1 votes
# Vyxal 3 `Rj`, 4 bytes

```
₅ᶻ2c

```

Try it Online!

rip -H flag

# Answer
> 1 votes
# Pip, 10 bytes

```
Lh2N Ui|Pi

```

Attempt This Online!

### Explanation

Flagless version, inspired by Xcali's Perl answer.

```
            i is preinitialized to 0
Lh          Loop 100 times:
     Ui      Increment i
  2N         Count occurrences of 2 in (the new value of) i
       |     If that is falsey (0), then
        Pi   Print i

```

# Answer
> 0 votes
# SmileBASIC, 50 bytes

```
@L
N=N+1IF.>INSTR(STR$(N),"2")THEN?N
ON N>99GOTO@L

```

### Explanation:

```
@LABEL
 N = N + 1
 IF 0 > INSTR(STR$(N), "2") THEN PRINT N
ON N>99 GOTO @LABEL

```

`INSTR(STR$(N), "2")` is -1 if `N` doesn't contain a 2.

`ON ... GOTO` takes a list of labels, and jumps to a label in that list corresponding to the value of an expression.
If N isn't greater than 99, `N>99` returns 0 so it jumps to the 0th label, `@LABEL`.
Otherwise, `N>99` is 1 so it tries to jump to label 1 in the list, but since the list isn't long enough, it doesn't jump and the program ends.

`ON` is meant to be used like `switch`/`case`, with a longer list of labels. But `ON x GOTO @LABEL` can be used as a shorter way of writing `IF !(x) GOTO @LABEL`:

```
IF N<=99GOTO@L
IF N<100GOTO@L
ON N>99GOTO@L

```

# Answer
> 0 votes
# ink, 34 bytes

```
-(i){("{i}"!?"2"):{i}}
{i<100:->i}

```

Try it online!

### Explanation

```
-(i)             // Labelled gather - keeps track of how many times it's been visited (in variable i)
{"{i}"!?"2":     // If "2" is not a substring of i...
{i}              // ...print i
}
{i<100:->i}      // If i is less than 100, go back to i.

```

# Answer
> 0 votes
# Vim, 18 bytes/keystrokes

```
100o0<esc>V{g<C-a>J:g/2/d<cr>

```

Try it online!

# Answer
> 0 votes
## C++, ~~84~~ 81 bytes

-3 bytes thanks to ceilingcat

The function needs a void return value to compile with MSVC

```
#include<cstdio>
void f(){for(int i=0;++i<101;)i%10-2&&i/10-2&&printf("%d\n",i);}

```

The `if` read as "if the first digit isn't 2 and the second digit isn't 2"

# Answer
> 0 votes
# Deadfish~

```
{iiiii}dc{dddd}ic{iiii}ic{dddd}dc{iiii}iic{dddd}ddc{iiii}iiic{dddd}dddc{iiii}iiiic{dddd}ddddc{iiii}iiiiic{dddd}dddddc{iiii}iiiiiic{dddd}ddddddc{iiiii}dddc{ddddd}iiic{iiii}dcdc{dddd}iic{iiii}dcc{dddd}ic{iiii}dciic{dddd}dc{iiii}dciiic{dddd}ddc{iiii}dciiiic{dddd}dddc{iiii}dciiiiic{dddd}ddddc{iiii}dciiiiiic{dddd}dddddc{iiii}dc{i}dddc{dddd}ddddddc{iiii}dc{i}ddc{ddddd}iiic{iiii}icdddc{dddd}iic{iiii}icddc{dddd}ic{iiii}icc{dddd}dc{iiii}icic{dddd}ddc{iiii}iciic{dddd}dddc{iiii}iciiic{dddd}ddddc{iiii}iciiiic{dddd}dddddc{iiii}iciiiiic{dddd}ddddddc{iiii}iciiiiiic{ddddd}iiic{iiii}iicddddc{dddd}iic{iiii}iicdddc{dddd}ic{iiii}iicdc{dddd}dc{iiii}iicc{dddd}ddc{iiii}iicic{dddd}dddc{iiii}iiciic{dddd}ddddc{iiii}iiciiic{dddd}dddddc{iiii}iiciiiic{dddd}ddddddc{iiii}iiciiiiic{ddddd}iiic{iiii}iiicdddddc{dddd}iic{iiii}iiicddddc{dddd}ic{iiii}iiicddc{dddd}dc{iiii}iiicdc{dddd}ddc{iiii}iiicc{dddd}dddc{iiii}iiicic{dddd}ddddc{iiii}iiiciic{dddd}dddddc{iiii}iiiciiic{dddd}ddddddc{iiii}iiiciiiic{ddddd}iiic{iiii}iiiicddddddc{dddd}iic{iiii}iiiicdddddc{dddd}ic{iiii}iiiicdddc{dddd}dc{iiii}iiiicddc{dddd}ddc{iiii}iiiicdc{dddd}dddc{iiii}iiiicc{dddd}ddddc{iiii}iiiicic{dddd}dddddc{iiii}iiiiciic{dddd}ddddddc{iiii}iiiiciiic{ddddd}iiic{iiii}iiiiic{d}iiic{dddd}iic{iiii}iiiiicddddddc{dddd}ic{iiii}iiiiicddddc{dddd}dc{iiii}iiiiicdddc{dddd}ddc{iiii}iiiiicddc{dddd}dddc{iiii}iiiiicdc{dddd}ddddc{iiii}iiiiicc{dddd}dddddc{iiii}iiiiicic{dddd}ddddddc{iiii}iiiiiciic{ddddd}iiic{iiii}iiiiiic{d}iic{dddd}iic{iiii}iiiiiic{d}iiic{dddd}ic{iiii}iiiiiicdddddc{dddd}dc{iiii}iiiiiicddddc{dddd}ddc{iiii}iiiiiicdddc{dddd}dddc{iiii}iiiiiicddc{dddd}ddddc{iiii}iiiiiicdc{dddd}dddddc{iiii}iiiiiicc{dddd}ddddddc{iiii}iiiiiicic{ddddd}iiic{iiiii}dddc{d}ic{dddd}iic{iiiii}dddc{d}iic{dddd}ic{iiiii}dddcddddddc{dddd}dc{iiiii}dddcdddddc{dddd}ddc{iiiii}dddcddddc{dddd}dddc{iiiii}dddcdddc{dddd}ddddc{iiiii}dddcddc{dddd}dddddc{iiiii}dddcdc{dddd}ddddddc{iiiii}dddcc{ddddd}iiic{iiii}dcdcc

```

---
Tags: code-golf, sequence, kolmogorov-complexity
---


title: What are my dimensions?

text:
# Question
Title: What are my dimensions?
**Task:** Given the area of a triangle, find a Heronian triangle with that area. Any Heronian triangle with the specified area is allowed.

A Heronian triangle is a triangle with **integer sides and integer area**. By Heron's formula, a triangle with sides lengths `a,b,c` has area

```
sqrt(s*(s-a)*(s-b)*(s-c))

```

where `s=(a+b+c)/2` is half the perimeter of the triangle. This can also be written as

```
sqrt((a+b+c)*(-a+b+c)*(a-b+c)*(a+b-c)) / 4

```

If no such triangle exists, output with a consistent falsey value.

**Input:** A single, positive integer representing the area of the triangle.

**Output:** Any three side lengths for such a triangle OR a falsely value.

Examples:

```
Input -> Output
6 -> 3 4 5
24 -> 4 15 13
114 -> 37 20 19
7 -> error

```

Standard loopholes apply

This is code golf, shortest answer in bytes wins.

# Answer
# Jelly, ~~17~~ 16 bytes

-1 byte thanks to Erik the outgolfer (make use of the quick, `¥`)

```
SHð;_P
ṗ3Ç⁼¥Ðf²Ḣ

```

Brute force application of Heron's formula.

**Try it online!** (reaches the 60s time out for the 114 tests case. Takes 3m 30s locally - it does check 1143 = 1,481,544 triples)

### How?

A true golf solution - given an area `a` it finds **all** tuples of three integers between `1` and `a` (even with repeated triangles and ones of no area), gets their area and filters for those with the desired area (it doesn't even stop as soon as one is found, it ploughs through them all and pops the first result afterwards). Yields `0` if none exists.

```
SHð;_P - Link 1, get the square of the area of a triangle: list of sides
S      - sum the sides (get the perimeter)
 H     - halve
  ð    - dyadic chain separation (call that p)
    _  - subtraction (vectorises) =    [p-side1,  p-side2,  p-side3]
   ;   - concatenate              = [p, p-side1,  p-side2,  p-side3]
     P - product                  =  p*(p-side1)*(p-side2)*(p-side3)
                                  = the square of Heron's formula = area squared

ṗ3Ç⁼¥Ðf²Ḣ - Main link: number a (area)
ṗ3        - third Cartesian power (all triples of [1,area] : [[1,1,1],[1,1,2],[1,2,1],[1,2,2],[2,1,1],[2,1,2],[2,2,1],[2,2,2], ... ,[a,a,a]]
       ²  - square a
     Ðf   - filter keep if:
    ¥     -   last two links as a dyad:
  Ç       -     call last link (1) as a monad f(list of sides)
   ⁼      -     left (that result) equals right (square of a)?
        Ḣ - head - get the first one (an empty list yields 0, perfect for the falsey case)

```
> 6 votes

# Answer
## JavaScript (ES7), ~~109~~ ~~102~~ ~~100~~ 98 bytes

Returns either an array of 3 integers or `false`. Like the Jelly answer, this is brute forcing Heron's formula.

```
A=>[...Array(A**3)].some((_,a)=>A*A/(r=[b=a/A%A|0,c=a/A/A|0,a%=A],p=a+b+c>>1)/(p-a)/(p-b)==p-c)&&r

```

### Test cases

```
let f =

A=>[...Array(A**3)].some((_,a)=>A*A/(r=[b=a/A%A|0,c=a/A/A|0,a%=A],p=a+b+c>>1)/(p-a)/(p-b)==p-c)&&r

console.log(JSON.stringify(f(6)))
console.log(JSON.stringify(f(24)))
console.log(JSON.stringify(f(114)))
console.log(JSON.stringify(f(7)))
```

---

## Recursive version, 83 bytes

Returns an array of 3 integers or throws a recursion error. Sadly, it only works for small inputs.

```
f=(A,n)=>A*A/(r=[a=n%A,b=n/A%A|0,c=n/A/A|0],p=a+b+c>>1)/(p-a)/(p-b)==p-c?r:f(A,-~n)

```

### Demo

```
f=(A,n)=>A*A/(r=[a=n%A,b=n/A%A|0,c=n/A/A|0],p=a+b+c>>1)/(p-a)/(p-b)==p-c?r:f(A,-~n)

console.log(JSON.stringify(f(6)))
console.log(JSON.stringify(f(24)))
```
> 5 votes

# Answer
# Haskell, 69 bytes

```
f a=take 1[t|t<-mapM(\_->[1..a])":-)",a*a==product[sum t/2-x|x<-0:t]]

```

Try it online!

Outputs a singleton of a list of three triangle sides like `[[3.0,4.0,5.0]]`. Impossible inputs give `[]`. Technically only `False` is Falsey for Haskell, but because Haskell requires all possible outputs to be of the same type, it can't be used. If an error could be used as Falsey, `[...]!!0` would save 3 bytes over `take 1[..]`.

Tries all triples `t` of possible side lengths each ranging from `1` to the area `a`. Heron's formula is used to check if the area matches via `(s-0)(s-x)(s-y)(s-z)==a*a` where `s=(x+y+z)/2` is `sum t/2`. The product `(s-0)(s-x)(s-y)(s-z)` is expressed as a `product` with elements taken from `0:t`, i.e. the triple as well as 0.
> 4 votes

# Answer
# Python 2 (PyPy), ~~131~~ ~~123~~ 118 bytes

```
n=input()
t=n*3;r=i=c=0
while c<t:
 i+=1;a,b,c=i%t,i/t%t,i/t/t;s=a+b+c>>1
 if(s-a)*s*(s-b)*(s-c)==n**2:r=a,b,c
print r

```

Try it online!

While this also works on CPython, PyPy is a lot faster and is able to compute the triangle for 114 in the time limit on TIO.

Timings from my machine:

```
$ echo 114 | time pypy2 d.py
        0.55 real         0.52 user         0.02 sys
$ echo 114 | time python2 d.py
       52.46 real        51.76 user         0.27 sys

```
> 2 votes

# Answer
# F#, ~~170~~ ~~156~~ 152 bytes

```
let f(a,b,c)=
 let s=(a+b+c)/2.0
 s*(s-a)*(s-b)*(s-c)
let g A=[for a in 1.0..A do for b in a..A do for c in b..A do yield a,b,c]|>List.find(f>>(=)(A*A))

```

Try it online!

# "Ungolfed"

```
let calculateArea (a, b, c) =
    let s = (a+b+c)/2.0
    s*(s-a)*(s-b)*(s-c)

let getTriangle A =
    [  for a in 1.0..A do
       for b in a..A do
       for c in b..A do yield a,b,c
    ]
    |> List.find(calculateArea>>(=)(A * A))

```

If there are no results found, the program will fault. If this is not desired, I have to replace `List.find` with either `List.filter` (+2 bytes) which will produce an empty list in case nothing is found or `List.tryFind` (+3 bytes), returning None in case no triangle was found.

I always find that a golfed F# version is still reasonable legible.
> 2 votes

# Answer
# Wolfram Language (Mathematica), 59 bytes

```
Solve[Area@SSSTriangle[a,b,c]==#>c>b>a>0,{a,b,c},Integers]&

```

Try it online!
> 2 votes

# Answer
# Pyth - 23 bytes

```
/mu*G-/sd2Hd/sd2^UQ3^Q2

```

Which prints a truthy/falsy value, or

```
fq^Q2u*G-/sT2HT/sT2^UQ3

```

which prints out all possible solutions, and is horribly slow for large inputs. Put 'h' at the beginning to only print one.

Explanation:

```
fq^Q2u*G-/sT2HT/sT2^UQ3
                    UQ    # List of numbers from 0 to input-1
                   ^  3   # All triples of these numbers
f                         # Filter this by the following test (on variable T, based on Hero's formula)
     u*G-/sT2HT/sT2       # s*(s-a)*(s-b)*(s-c), where s is the sum of the triple over 2 (calclated as /sT2 )
 q^Q2                     # Test if equal to input ^2

```

Try it
> 1 votes

# Answer
# Perl 6, 54 bytes

```
->\a{first {a*a==[*] .sum/2 «-«(0,|$_)},[X] ^a xx 3}

```

Brute force search of all possibles sides up to one less than `a`, the input area.

* `^a` is the range of numbers from 0 to `a - 1`.
* `[X] ^a xx 3` reduces, by cross product, three copies of that range, producing all triplets from `(0, 0, 0)` to `(a - 1, a - 1, a - 1)`.
* We look for the `first` triplet such that the area of the triangle with those sides equals `a`, using Heron's formula.

Within the code block given to `first`:

* `$_` is the triplet. Call it `(x, y, z)` here.
* `(0,|$_)` is the same triplet but with `0` prepended: `(0, x, y, z)`.
* `.sum / 2` is half the perimeter (a quantity which is named `s` in the usual expression of Heron's formula).
* `.sum / 2 «-« (0, |$_)` is the subtraction hyperoperator with `s` on the left and the `(0, x, y, z)` on the right, giving `(s - 0, s - x, s - y, s - z)`.
* `[*]` then reduces that quadruplet with multiplication, giving the square of the area.
* `a * a ==` looks for a squared area equal to the square of the given area.

If no triplet is found, `Nil` (which is falsey) is returned.
> 1 votes

# Answer
## Mathematica, 77 bytes

with mathematica's **Solve**

```
s=(a+b+c)/2;d=Sqrt[s(s-a)(s-b)(s-c)];Solve[d==#&&0<a<b<c<#,{a,b,c},Integers]&

```

---

## Mathematica, 117 bytes

brute force

```
s=(a+b+c)/2;l="error";(For[a=1,a<#,a++,For[b=1,b<a,b++,For[c=1,c<b,c++,If[Sqrt[s(s-a)(s-b)(s-c)]==#,l={a,b,c}]]]];l)&

```
> 1 votes

# Answer
# Haskell, 76 bytes

```
f s=[[a,b,c]|a<-[1..s],b<-[1..a],c<-[1..b],a*a*c*c-(a*a+c*c-b*b)^2/4==4*s*s]

```

This outputs a list of lists containing all possible integral sizes that generate the correct area via brute force (outputting the empty list if there are none). The caveat being it outputs them as doubles because of that division in the middle but their fractional part is always 0.

If you for some reason can't take that,

```
f s=[[a,b,c]|a<-[1..s],b<-[1..a],c<-[1..b],4*a*a*c*c-(a*a+c*c-b*b)^2==16*s*s]

```

This will output the answers as a list of integer lists for ~~89~~ 77 bytes total or ~~13~~ 1 extra bytes. (Thanks to Neil)

If you need / want only the first element just putting `!!0` at the end will give you only the first element if there are numbers that apply and an error if there's none for 3 more bytes and `take 1` at the beginning will take the first element without erroring out for 6 more bytes.

Try it online!
> 1 votes

# Answer
# TI-Basic, ~~70~~ 69 bytes

```
Prompt A
For(B,1,A
For(C,1,B
For(D,1,C
(B+C+D)/2
If A<sup>2</sup>=Ansprod(Ans-{B,C,D
Then
Disp B,C,D
Return
End
End
End
End
/
```

Displays the three side lengths if there is a triangle, throws a syntax error if there isn't (thanks to the `/` at the end).

-1 byte thanks to Sean's comment on a different answer
> 0 votes

# Answer
# Actually, 22 bytes

```
;╗R3@∙⌠;Σ½;)♀-π*╜²=⌡░F

```

Try it online!

Explanation:

```
;╗R3@∙⌠;Σ½;)♀-π*╜²=⌡░F  (implicit input: A)
;╗                      store a copy of A in register 0
  R                     range(1, A+1)
   3@∙                  ternary Cartesian product (all triples with values in [1, A])
      ⌠;Σ½;)♀-π*╜²=⌡░   filter: take triples where function returns truthy
       ;Σ½                make a copy of the triple, compute s = (a+b+c)/2
          ;)              make a copy of s, move it to the bottom of the stack
            ♀-            subtract each value in the triple from s
              π*          product of those values and s (s*(s-a)*(s-b)*(s-c))
                ╜²        A*A
                  =       compare equality (does area of triangle with given dimensions equal input?)
                     F  take first triple that satisfies the filter (or empty list if none)

```
> 0 votes

# Answer
# Casio Basic, 123 bytes

```
For 1⇒a To n
For 1⇒b To n
For 1⇒c To n
If(s*(s-a)*(s-b)*(s-c)|s=(a+b+c)/2)=n^2
Then
Print{a,b,c}
Stop
IfEnd
Next:Next:Next

```

Standard brute force solution. 122 bytes for the code, 1 byte to specify `n` as a parameter.
> 0 votes

# Answer
# Perl 5, 119 + 2 `-pa` = 121 bytes

```
for$a(1..$_){for$b(1..$_){map{($t=($s=($a+$b+$_)/2)*($s-$a)*($s-$b)*($s-$_))>0&&"@F"==sqrt$t&&($\="$a $b $_")}1..$_}}}{

```

Try it online!
> 0 votes

# Answer
# JavaScript (Node.js), 90 bytes

```
S=>(g=(a,b,c,r=(a+b+c)/2)=>r*(r-a)*(r-b)*(r-c)^S*S?!c&&g(S,a,b)||--a&&g(a,b,c):[a,b,c])(S)

```

Try it online!

# JavaScript (Node.js), 92 bytes

```
S=>(g=(a,b,c,r=(a+b+c)/2)=>(c?r*(r-a)*(r-b)*(r-c)==S*S&&[a,b,c]:g(S,a,b))||--a&&g(a,b,c))(S)

```

Try it online!

Usual search

Where's the proof every length \<= area?
> 0 votes

# Answer
# Uiua, 54 Bytes

Standard bruteforce solution. Returns all possible results.

```
▽=⊙:≡(√/×⊂-:⊙:.÷2/+.).☇1+1⇡⊂⊂...

```

Try It

Explanation:

```
▽=⊙:≡(√/×⊂-:⊙:.÷2/+.).☇1+1⇡⊂⊂...
                       ☇1+1⇡⊂⊂... # generate tuples [1, a]^3
                      . # save a copy to output
    ≡(√/×⊂-:⊙:.÷2/+.) # for each side length tuple calculate the area
                    . # save a copy of the current tuple so we can do s-a,s-b,s-c later
                ÷2/+ # calculate s by summing and dividing by 2
               . # copy s so we can multiply by it later
           :⊙: # bring the saved tuple to the top of the stack
          - # calculate s-a,s-b,s-c
         ⊂ # join s to the array containing [s-a,s-b,s-c]
       /× # reduce multiply to get the product of all of the elements
      √ # final square root to calculate area
  ⊙: # bring area we are looking for up to the second position in the stack
 = # create a boolean mask which selects all areas which matched
▽ # keep the tuples that had the correct area

```
> 0 votes

---
Tags: code-golf, geometry
---


title: That's a prime... almost

text:
# Question
Title: That's a prime... almost
If you've ever learned about primes in math class, you've probably have had to, at one point, determine if a number is prime. You've probably messed up while you were still learning them, for example, mistaking 39 for a prime. Well, not to worry, as 39 is a semiprime, i.e., that it is the product of two primes.

Similarly, we can define a *k*-almost prime as being the product of *k* prime numbers. For example, 40 is the 4th 4-almost prime; 40 = 5\*2\*2\*2, the product of 4 factors.

Your task is to write a program/function that accepts two integers *n* and *k* as input and output/return the *n*th *k*-almost prime number. This is a code-golf, so the shortest program in bytes wins.

## Test cases

```
n, k => output
n, 1 => the nth prime number
1, 1 => 2
3, 1 => 5
1, 2 => 4
3, 2 => 9
5, 3 => 27

```

# Miscellaneous

You have to generate the primes yourself by any means other than a simple closed form, if such a closed form exists.

# Answer
> 7 votes
## Pyth, 9 bytes

```
e.fqlPZQE

```

Explanation

```
          - autoassign Q = eval(input())
     PZ   -      prime_factors(Z)
    l     -     len(^)
   q   Q  -    ^ == Q
 .f     E -  first eval(input()) of (^ for Z in range(inf))
e         - ^[-1]

```

Try it here!

Or try a test suite!

# Answer
> 6 votes
# Brachylog, 9 bytes

Beating @sundar by using half as much bytes

```
{~l~ḋ}ᶠ⁽t

```

# Explanation

```
                    --  Input like [n,k]
{    }ᶠ⁽            --      Find the first n values which
   ~ḋ               --          have a prime decomposition
 ~l                 --          of length k
        t           --      and take the last one

```

Try it online!

# Answer
> 5 votes
# Jelly, 9 bytes

```
ÆfL=³
ç#Ṫ

```

Try it online!

### How it works

```
Ç#Ṫ    Main link. Left input: k. Right input: n.

Ç      Apply the helper link to k, k + 1, k + 2, ... until...
 #       n matches are found.
  Ṫ    Retrieve the last match.

ÆfL=³  Helper link. Left argument: k (iterator)

Æf     Yield the prime factors of k.
  L    Compute the length of the list, i.e., the number of prime factors.
   =³  Compare the result with k (left input).

```

# Answer
> 4 votes
## Pyke (commit 29), 8 bytes (noncompetitive)

```
.fPlQq)e

```

Explanation:

```
         - autoassign Q = eval_or_not(input())
.f    )  - First eval_or_not(input) of (^ for i in range(inf))
  P      -    prime_factors(i)
   l     -   len(^)
     q   -  ^==V
    Q    -   Q
       e - ^[-1]

```

# Answer
> 4 votes
# Julia, ~~84~~ ~~78~~ ~~59~~ 57 bytes

```
f(n,k,i=1)=n>0?f(n-(sum(values(factor(i)))==k),k,i+1):i-1

```

This is a recursive function that accepts two integers and returns an integer. The approach here is to check the sum of the exponents in the prime factorization against `k`.

Ungolfed:

```
function f(n, k, i=1)
    # We initialize a counter i as a function argument.

    # Recurse while we've encountered fewer than n k-almost primes
    if n > 0
        # If the sum of the exponents in the prime factorization of i is
        # equal to k, there are k prime factors of i. We subtract a boolean
        # from n, which is implicitly cast to an integer, which will
        # decrement n if i is k-almost prime and leave it as is otherwise.
        return f(n - (sum(values(factor(i))) == k), k, i + 1)
    else
        # Otherwise we return i-1 (i will have been incremented one too
        # many times, hence the -1)
        return i - 1
    end
end

```

# Answer
> 4 votes
# Vyxal, 8 bytes

```
λǐL⁰=;ȯt

```

Try it Online!

```
λ    ;ȯt # Nth number where
 ǐL      # Prime factor length
   ⁰=    # Equal to input

```

# Answer
> 3 votes
# Brachylog, 18 bytes

```
,1{hH&t<NḋlH;N}ⁱ⁽t

```

Try it online!

```
                      Implicit input, say [5, 3]
,1                    Append 1 to the input list. [5, 3, 1]
  {           }ⁱ⁽     Repeat this predicate the number of times given by
                        the first element of the list (5),
                        on the rest of the list [3, 1]
   hH&                Let's call the first element H
      t<N             There is a number N greater than the second element
         ḋ            Whose prime factorization's
          l           length
           H          is equal to H
            ;N        Then, pair that N with H and let that be input for
                      the next iteration
                 t    At the end of iterations, take the last N
                      This is implicitly the output

```

# Answer
> 2 votes
# Sidef, 21 bytes

```
nth_almost_prime(n,k)

```

# Answer
> 1 votes
# Mathematica, ~~56~~ 51 bytes

```
Last@Select[Range[2^##],PrimeOmega@#==n&/.n->#2,#]&

```

Warning: This is theoretical. Do not run for any values\>4. Replace 2^## with a more efficient expression.

# Answer
> 1 votes
# Mathematica, ~~53~~ 49 Bytes

```
Cases[Range[2^(#2+#)],x_/;PrimeOmega@x==#2][[#]]&

```

Generates a list of integers based on a loose upper bound. `PrimeOmega` counts the prime factors with multiplicities, the *k*-almost prime `Cases` are taken from the list, and the *n*th member of that subset is returned.

# Answer
> 1 votes
# Haskell, 88 bytes

Can probably be golfed a lot more, as I'm still a newbie to Haskell. The function `q` returns the number of factors of its argument, and `f` uses that to get take the `nth` element of a list made from all numbers that have `k` factors.

```
q n|n<2=0|1>0=1+q(div n ([x|x<-[2..],mod n x<1]!!0))
f n k=filter(\m->q m==k)[1..]!!n-1

```

# Answer
> 1 votes
# MATL, 14 bytes

```
:YqiZ^!XpSu1G)

```

Try it on MATL Online

```
:               % Take first input n implicitly, make range 1 to n
 Yq             % Get corresponding prime numbers (1st prime to nth prime)
   i            % Take the second input k
    Z^          % Take the k-th cartesian power of the primes list
                % (Getting all combinations of k primes)
      !Xp       % Multiply each combination (2*2*2, 2*2*3, 2*2*5, ...)
         Su     % Sort and unique
           1G)  % Take the n-th element of the result

```

# Answer
> 0 votes
# Python 3, 100 bytes

This is a very simple brute force function. It checks every number starting from 2 with `sympy`'s `factorint` function until it has found `n` `k`-almost primes, at which point, the function returns the `n`th of these.

```
import sympy
def a(n,k):
 z=1;c=0
 while c<n:z+=1;c+=(sum(sympy.factorint(z).values())==k)
 return z

```

**Ungolfed:**

I use `sum(factorint(a).values())` because `factorint` returns a dictionary of `factor: exponent` pairs. Grabbing the values of the dictionary (the exponents) and summing them tells me how many prime factors there are and thus what `k` this `k`-almost prime is.

```
from sympy import factorint
def almost(n, k):
    z = 1
    count = 0
    while count < n:
        z += 1
        if sum(factorint(a).values()) == k:
            count += 1
    return z

```

# Answer
> 0 votes
# Python 2, 76 bytes

```
f=lambda n,k,p=2,c=0:c==k if p>n else f(n,k,p+1,c)if n%p else f(n/p,k,p,c+1)

```

Try it online!

---
Tags: code-golf, math, number, number-theory, primes
---


title: Is it almost-prime?

text:
# Question
Title: Is it almost-prime?
Sandbox

**Definition:** A positive integer `n` is *almost-prime*, if it can be written in the form `n=p^k` where `p` is a prime and `k` is also a positive integers. In other words, the prime factorization of `n` contains only the same number.

**Input:** A positive integer `2<=n<=2^31-1`

**Output:** a truthy value, if `n` is *almost-prime*, and a falsy value, if not.

**Truthy Test Cases:**

```
2
3
4
8
9
16
25
27
32
49
64
81
1331
2401
4913
6859
279841
531441
1173481
7890481
40353607
7528289

```

**Falsy Test Cases**

```
6
12
36
54
1938
5814
175560
9999999
17294403

```

Please do not use standard loopholes. This is so the shortest answer in bytes wins!

# Answer
# Sagemath, 2 bytes

```
GF

```

Outputs via exception.

Try it online!

---

The Sagemath builtin \\$\text{GF}\\$ creates a Galois Field of order \\$n\\$. However, remember that \\$\mathbb{F}\_n\\$ is only a field if \\$n = p^k\\$ where \\$p\\$ is a prime and \\$k\\$ a positive integer. Thus the function throws an exception if and only if its input is not a prime power.
> 51 votes

# Answer
# Python 2, 42 bytes

```
f=lambda n,p=2:n%p and f(n,p+1)or p**n%n<1

```

Try it online!

Since Python doesn't have any built-ins for primes, we make do with checking divisibility.

We find the smallest prime `p` that's a factor of `n` by counting up `p=2,3,4,...` until `n` is divisible by `p`, that is `n%p` is zero. There, we check that this `p` is the only prime factor by checking that a high power of `p` is divisible by `n`. For this, `p**n` suffices.

As a program:

**43 bytes**

```
n=input()
p=2
while n%p:p+=1
print p**n%n<1

```

Try it online!

This could be shorter with exit codes if those are allowed.

**46 bytes**

```
lambda n:all(n%p for p in range(2,n)if p**n%n)

```

Try it online!
> 15 votes

# Answer
# Shakespeare Programming Language, 329 bytes

```
,.Ajax,.Page,.Act I:.Scene I:.[Enter Ajax and Page]
Ajax:Listen tothy.
Page:You cat.
Scene V:.
Page:You is the sum ofYou a cat.
 Is the remainder of the quotient betweenI you nicer zero?If soLet usScene V.
Scene X:.
Page:You is the cube ofYou.Is you worse I?If soLet usScene X.
 You is the remainder of the quotient betweenYou I.Open heart

```

Try it online!

Outputs `0` if the input is almost prime, and a positive integer otherwise. I am not sure this is an acceptable output; changing it would cost a few bytes.

Explanation:

* Scene I: `Page` takes in input (call this `n`). Initialize `Ajax = 1`.
* Scene V: Increment `Ajax` until `Ajax` is a divisor of `Page`; call the final value `p` This gives the smallest divisor of `Page`, which is guaranteed to be a prime.
* Scene X: Cube `Ajax` until you end up with a power of `p`, say `p^k` which is greater than `n`. Then `n` is almost-prime iff `n` divides `p^k`.
> 13 votes

# Answer
# MATL, 4 bytes

```
Yf&=

```
* For almost-primes the output is a matrix containing only `1`s, which is truthy.
* Otherwise the output is a matrix containing several `1`s and at least one `0`, which is falsy.

Try it online! Or verify all test cases, including truthiness/falsihood test.

### How it works

```
     % Implicit input
Yf   % Prime factors. Gives a vector with the possibly repeated prime factors
&=   % Matrix of all pair-wise equality comparisons
     % Implicit output

```
> 12 votes

# Answer
# Wolfram Language (Mathematica), 11 bytes

```
PrimePowerQ

```

Try it online!

@Sisyphus saved 1 byte
> 10 votes

# Answer
# 05AB1E, 2 bytes

```
ÒË

```

Try it online!

### Commented:

```
Ò   -- Are all the primes in the prime decomposition
 Ë  -- Equal?

```
> 9 votes

# Answer
# , ~~36~~ ~~32~~ 29 bytes

*-3 bytes by outputting a vector of booleans without extracting the first element*

```
!(a=2:(n=scan()))[!n%%a]^n%%n

```

Try it online!

Outputs a vector of booleans. In R, a vector of booleans is truthy iff the first element is `TRUE`.

First, find the smallest divisor `p` of `n`. We can do this by checking all integers (not only primes), as the smallest divisor of an integer (apart from 1) is always a prime number. Here, let `a` be all the integers between `2` and `n`, then `p=a[!n%%a][1]` is the first element of `a` which divides `n`.

Then `n` is almost prime iff `n` divides `p^n`.

This fails for any moderately large input, so here is the previous version which works for most larger inputs:

# , ~~36~~ 33 bytes

```
!log(n<-scan(),(a=2:n)[!n%%a])%%1

```

Try it online!

Compute the logarithm of `n` in base `p`: this is an integer iff `n` is almost prime.

This will fail due to floating point inaccuracy for certain (but far from all) large-ish inputs, in particular for one test case: \\$4913=17^3\\$.
> 9 votes

# Answer
# C (gcc), 43 bytes

```
f(n,i){for(i=1;n%++i;);n=i<n&&f(n/i)^i?:i;}

```

Try it online!

Returns `p` if `n` is almost-prime, and `1` otherwise.

```
f(n,i){
    for(i=1;n%++i;);    // identify i = the least prime factor of n
    n=i<n&&f(n/i)^i     // if n is neither prime nor almost-prime
      ?                 //  return 1
      :i;               // return i
}

```
> 8 votes

# Answer
# APL (Dyalog Unicode), 7 bytes

```
⊢∊⍳∘.∧⍳

```

Try it online!

Uses `⎕IO←0`. Returns 0 if the input is almost-prime, 1 otherwise.

### How it works

```
⊢∊⍳∘.∧⍳    ⍝ Input: integer n ≥ 2
  ⍳∘.∧⍳    ⍝ Generate a table of LCMs over 0..n-1
⊢∊         ⍝ Does the table contain n?

```

The LCM of two numbers is equivalent to taking the maximum of powers in their prime factorizations. If `n = p^k`, any numbers smaller than `n` cannot have `p^k` in their prime factorization, so the LCM table does not contain `n`. Otherwise, we can find a pair of coprime numbers under `n` that multiplies to `n`, so the LCM table is guaranteed to contain at least one copy of `n`.
> 8 votes

# Answer
# APL (Dyalog Classic), ~~33~~ ~~31~~ 26 bytes

```
{⍵∊∊(((⊢~∘.×⍨)1↓⍳)⍵)∘*¨⍳⍵}

```

-5 bytes from Kevin Cruijssen's suggestion.

*Warning:* Very, very slow for larger numbers.

## Explanation

```
{⍵∊∊(((⊢~∘.×⍨)1↓⍳)⍵)∘*¨⍳⍵} ⍵=n in all the following steps
                       ⍳⍵  range from 1 to n
                    ∘*¨    distribute power operator across left and right args
    (((⊢~∘.×⍨)1↓⍳)⍵)       list of primes till n
   ∊                       flatten the right arg(monadic ∊)
 ⍵∊                        is n present in the primes^(1..n)?

```

Try it online!
> 7 votes

# Answer
# , 9 8 bytes

```
1=#@=@q:

```

Try it online!

*-1 byte thanks to xash*

Tests if the self-classify `=` of the prime factors `q:` has length `#` equal to one `1=`
> 6 votes

# Answer
## Setanta, ~~61~~ 59 bytes

```
gniomh(n){p:=2nuair-a n%p p+=1nuair-a n>1 n/=p toradh n==1}

```

Try it here

Notes:

* The proper keyword is `gníomh`, but Setanta allows spelling it without the accents so I did so to shave off a byte.
> 6 votes

# Answer
# Pyth, 4 bytes

```
!t{P

```

Try it online!

Explanation:

```
P - List of prime factors
{ - Remove duplicate elements
t - Removes first element
! - Would return True if remaining list is empty, otherwise False

```

*-1 byte, thanks to hakr14*
> 5 votes

# Answer
# JavaScript (ES6), 43 bytes

## Without BigInts

Returns a Boolean value.

```
f=(n,k=1)=>n%1?!~~n:f(n<0?n/k:n%++k?n:-n,k)

```

Try it online!

A recursive function that first looks for the smallest divisor \\$k\>1\\$ of \\$n\\$ and then divides \\$-n\\$ by \\$k\\$ until it's not an integer anymore. (The only reason why we invert the sign of \\$n\\$ when \\$k\\$ is found is to distinguish between the two steps of the algorithm.)

If \\$n\\$ is almost-prime, the final result is \\$-\dfrac{1}{k}\>-1\\$. So we end up with \\$\lceil n\rceil=0\\$.

If \\$n\\$ is not almost-prime, there exists some \\$q\>k\\$ coprime with \\$k\\$ such that \\$n=q\times k^{m}\\$. In that case, the final result is \\$-\dfrac{q}{k}\<-1\\$. So we end up with \\$\lceil n\rceil\<0\\$.

---

# JavaScript (ES11), 33 bytes

## With BigInts

With BigInts, using @xnor's approach is probably the shortest way to go.

Returns a Boolean value.

```
f=(n,k=1n)=>n%++k?f(n,k):k**n%n<1

```

Try it online!
> 4 votes

# Answer
# Regex (ECMAScript), ~~35~~ ~~33~~ 32 bytes

*-2 bytes thanks to H.PWiz; the explanation for why this worked was more complicated*
*-1 bytes by returning to the original algorithm (with its simple explanation), by actually constructing values of \\$a\\$ not divisible by \\$b\\$ (32 bytes) instead of asserting \\$a\\$ is not divisible by \\$b\\$ (35 bytes); this is slower, but not exponentially so*

```
^(?!(((x+)x+)(?=\2+$)\2*\3)\1+$)

```

Try it online!

The 35 byte version was written in 2014 by teukon and me.

This works by asserting that there do not exist any \\$a\\$ and \\$b\\$, both proper divisors of \\$n\\$ where \\$a\>b\\$, for which \\$a\\$ is not divisible by \\$b\\$.

This will always be true when \\$n\\$ is of the form \\$p^k\\$ (a prime power), because we will have \\$a=p^c\\$ and \\$b=p^d\\$ where \\$k \> c \> d \ge 0\\$, thus \\$a\\$ will always be divisible by \\$b\\$.

But if \\$n\\$ is not of the form \\$p^k\\$, there will always be at least one counterexample \\$a,b\\$ such that \\$a\\$ is not divisible by \\$b\\$. Trivially we can choose two different prime factors of \\$n\\$, and they will not be mutually divisible.

This algorithm is similar to that used by Original Original Original VI's answer.

```
# For the purpose of these comments, the input number will be referred to as N.
^(?!              # Assert that the following cannot match
    (             # Capture \1 to be the following:
        ((x+)x+)  # Cycle through all values of \3 and \2 such that \2 > \3 > 1
        (?=\2+$)  # such that \2 is a proper divisor of N
        \2*\3     # Cycle through all values of \1 > \2 that aren't divisible
                  # by \2, by letting \1 = \2 * A + \3 where A >= 0
    )
    \1+$          # where \1 is a proper divisor of N
)

```

---

Bonus: Here is a 28 (27) byte regex that matches numbers of the form \\$p^k\\$ where \\$0 \le k \le 2\\$:
`^(?!((x+)x+)(?!\1*\2+$)\1+$)`, exponential slowdown version: `^(?!((x+)+)(?!\1*\2+$)\1+$)`
(`(x+)+)` is equivalent to `(x+)x*` but exponentially slower)

Try it online!

This is interesting because if I'd set out to implement that function intentionally, I would have come up with something like `^(?=(x?x+?)\1*$)((?=(x+)(\3+$))\4)?\1$` (38 bytes), which is 10 bytes longer.

It was inspired by the algorithm used by Bubbler's APL answer. The full prime power version of that would be:
`^(?!((x+)(?=\2+$)x+)(?!\1*\2+$)\1+$)` \- ECMAScript, 36 bytes
`^(?!((x+)x+)\B(?>\1*?(?<=^\2+))$)` \- .NET, 33 bytes
`^(?!((x+)+)\B(?>\1*?(?<=^\2+))$)` \- .NET, 32 bytes, exponential slowdown

And user41805's APL answer ported to regex is:
`^(?!(xx+)\1*(?=\1*$)x(xx+)\2*$(?<=^\2+))` \- ECMAScript 2018, 40 bytes
`^(?!(?*(xx+)\1*$)(xx+)\2*(?=\2*$)x\1*$)` \- ECMAScript + `(?*)`, 39 bytes

The algorithm used by 10+ of the other answers (that all the prime factors are the same / there is only one prime factor), ported to regex is:
`^(?=(xx+?)\1*$)(?!(\1x+)(?<!^\3+(xx+))\2*$)` \- ECMAScript 2018, 43 bytes

# Retina 0.8.2, ~~41~~ ~~39~~ 38 bytes

```
.+
$*
^(?!(((1+)1+)(?=\2+$)\2*\3)\1+$)

```

Try it online!
> 4 votes

# Answer
# Io, 48 bytes

Port of @RobinRyder's R answer.

```
method(i,c :=2;while(i%c>0,c=c+1);i log(c)%1==0)

```

Try it online!

## Explanation

```
method(i,            // Take an input
    c := 2           // Set counter to 2
    while(i%c>0,     // While the input doesn't divide counter:
        c=c+1        //     Increment counter
    )
    i log(c)%1==0    // Is the decimal part of input log counter equal to 0?
)

```
> 3 votes

# Answer
# GAP 4.7, 31 bytes

`n->Length(Set(FactorsInt(n)))<2`

This is a lambda. For example, the statement

`Filtered([2..81], n->Length(Set(FactorsInt(n)))<2 );`

yields the list `[ 2, 3, 4, 5, 7, 8, 9, 11, 13, 16, 17, 19, 23, 25, 27, 29, 31, 32, 37, 41, 43, 47, 49, 53, 59, 61, 64, 67, 71, 73, 79, 81 ]`.

Try it online!
> 3 votes

# Answer
# Haskell, 36 bytes

```
f n=mod(until((<1).mod n)(+1)2^n)n<1

```

Try it online!

**36 bytes**

```
f n=and[mod(gcd d n^n)n<2|d<-[1..n]]

```

Try it online!

**39 bytes**

```
f n=all((`elem`[1,n]).gcd n.(^n))[2..n]

```

Try it online!

**39 bytes**

```
f n=mod n(n-sum[1|1<-gcd n<$>[1..n]])<1

```

Try it online!

**40 bytes**

```
f n=and[mod(p^n)n<1|p<-[2..n],mod n p<1]

```

Try it online!
> 3 votes

# Answer
# Factor, 35 bytes

```
: f ( n -- ? ) factors all-equal? ;

```

Try it online!
> 3 votes

# Answer
# Java, ~~69~~ 64 bytes

```
n->{int f=0,t=1;for(;n%++t>0;);for(;n>1;n/=t)f|=n%t;return f<1;}

```

-5 bytes thanks to *@Deadcode*.

Try it online.

**Explanation:**

```
n->{             // Method with integer parameter and boolean return-type
  int f=0,       //  Flag-integer `f`, starting at 0
      t=1;       //  Temp integer `t`, starting at 1
  for(;n%++t>0;);//  Increase `t` by 1 before every iteration with `++t`,
                 //  And continue looping until the input `n` is divisible by `t`
  for(;n>1;      //  Then start and continue a second loop as long as `n` is not 0 or 1:
      n/=t)      //    After every iteration: divide `n` by `t`
    f|=          //   Bitwise-OR the flag by:
       n%t;      //    `n` modulo-`t`
  return f<1;}   //  After both loops, return whether the flag is still 0

```

---

If we would be allowed to ignore floating point inaccuracies, a port of *@RobinRyder*'s R answer would be **64 bytes** as well:

```
n->{int m=1;for(;n%++m>0;);return Math.log(n)/Math.log(m)%1==0;}

```

Try it online.

**Explanation:**

```
n->{               // Method with integer parameter and boolean return-type
  int m=1;         //  Minimum divisor integer `m`, starting at 1
  for(;n%++m>0;);  //  Increase `m` by 1 before every iteration with `++m`
                   //  And continue looping until the input `n` is divisible by `m`
  return Math.log(n)/Math.log(m)
                   //  Calculate log_m(n)
         %1==0;}   //  And return whether it has no decimal values after the comma

```

But unfortunately this approach fails for test case `4913` which would become `2.9999999999999996` instead of `3.0` due to floating point inaccuracies (it succeeds for all other test cases).
A potential fix would be **71 bytes**:

```
n->{int m=1;for(;n%++m>0;);return(Math.log(n)/Math.log(m)+1e9)%1<1e-8;}

```

Try it online.
> 3 votes

# Answer
# Retina 0.8.2, ~~50~~ 43 bytes

```
.+
$*
^(?=(11+?)\1*$)((?=(1+)(\3+$))\4)*\1$

```

Try it online! Link includes faster test cases. Originally based on @Deadcode's answer to Match strings whose length is a fourth power, but saved 7 bytes thanks to @Deadcode by improving the basic algorithm. Explanation:

```
.+
$*

```

Convert the input to unary.

```
^(?=(11+?)\1*$)

```

Start by matching the smallest factor `p` of `n`. (`p` is necessarily prime, of course.)

```
(?=(1+)(\3+$))

```

Find `n`s largest proper factor `m`, which is equivalent to `n` divided by its smallest prime factor `q` (which will be equal to `p` on the first pass).

```
\4

```

The factorisation also captures `n-m`, which is subtracted from the current value of `n`, effectively dividing `n` by `q` for the next pass of the loop.

```
(...)*\1$

```

Repeat this division by the smallest prime factor until `n` becomes `p`, which is only possible if `n` is a power of `p`.
> 3 votes

# Answer
# Assembly (MIPS, SPIM), 238 bytes, 6 * 23 = 138 assembled bytes

```
main:li$v0,5
syscall
move$t3,$v0
li$a0,0
li$t2,2
w:bgt$t2,$t3,d
div$t3,$t2
mfhi$t0
bnez$t0,e
add$a0,$a0,1
s:div$t3,$t2
mfhi$t0
bnez$t0,e
div$t3,$t3,$t2
b s
e:add$t2,$t2,1
b w
d:move$t0,$a0
li$a0,0
bne$t0,1,p
add$a0,$a0,1
p:li$v0,1
syscall

```

Try it online!
> 3 votes

# Answer
# Brachylog, 2 bytes

Are all prime factors equal?

```
ḋ=

```

Try it online!
> 3 votes

# Answer
# APL (Dyalog Unicode) 17.0, 7 bytes

```
⍸2⌊/⊢∨⍳

```

Try it online!

Uses a different approach from Bubbler's answer, but only works for Dyalog 17.X. Errors with a domain error on non-prime powers, and doesn't error on truthy inputs.

The train is decomposed as the following

```
┌─┬─────────────────┐
│⍸│┌─┬─────┬───────┐│
│ ││ │┌─┬─┐│┌─┬─┬─┐││
│ ││2││⌊│/│││⊢│∨│⍳│││
│ ││ │└─┴─┘│└─┴─┴─┘││
│ │└─┴─────┴───────┘│
└─┴─────────────────┘

```

First a range from 1 to the right argument is created using .

```
      (⍳) 10
1 2 3 4 5 6 7 8 9 10

```

Then each value in this list is GCDed  with the right argument .

```
      (⊢∨⍳) 10
1 2 1 2 5 2 1 2 1 10

```

Then the pairwise minimum is taken, with the pairs overlapping, so `2⌊/1 3 2` is equivalent to `(1⌊3)(3⌊2)`.

```
      (2⌊/⊢∨⍳) 10
1 1 1 2 2 1 1 1 1

```

Monadic  in Dyalog 17.0 is a function that finds the indices of truthy values given a binary array, but this function of it is irrelevant for this solution. If the input is not a prime power, it will have at least one number greater than 1 when the above is performed (proof below). Otherwise if it is a prime power, the above will result in a list with only 1s. So applying  on a non-prime power will cause the function to error because its argument is not a binary array, whereas on a prime power it won't error because the argument would binary consisting only of 1s.

In Dyalog 18.0  has been extended to also accept non-binary arrays, so the above won't work. Instead, using 'unique'  in place of  will return the 1-length vector consisting only of 1 for truthy values, and a longer vector for falsey values.

Bubbler gave the following proof as to why `2⌊/⊢∨⍳` does not give a vector of 1s for falsey values.

Consider the Diophantine equation \\$p\_1a-p\_2b=1\\$, where \\$p\_1\\$ and \\$p\_2\\$ are distinct prime factors of a non-prime tower \\$N\\$ and \\$a,b\>0\\$. This equation has solutions, a proof of which can be found in the following Wikipedia article. What this equation means is that you will have a situation where a multiple of \\$p\_1\\$ occurs as the number immediately following a multiple of \\$p\_2\\$. Since each prime factor divides the input \\$N\\$, their multiple, when GCDed with the input, will result in a value greater than 1. The fact that these multiples are less than \\$N\\$ is left as an exercise to the reader. So the two multiples of prime numbers following one another and that these multiples are less than \\$N\\$ mean that you have a situation where `2⌊/⊢∨⍳` will have a number greater than 1 in it.

This situation does not occur for prime powers because given any two prime factors \\$p^m\\$ and \\$p^n\\$ where \\$n\>m\\$, there will never be a situation where \\$p^na-p^mb=1\\$ because that would imply \\$p(p^{n-1}a-p^{m-1}b)=1\\$, i.e. that \\$p\\$ divides 1 which is false.
> 3 votes

# Answer
# MathGolf, 10 bytes

```
╒g¶mÉk╒#─╧

```

Port of *@Razetime*'s APL (Dyalog Classic) answer, so make sure to upvote him as well!

Try it online.

**Explanation:**

```
╒           # Push a list in the range [1, (implicit) input-integer)
 g          # Filter it by:
  ¶         #  Check if it's a prime
   m        # Map each prime to,
    É       # using the following three operations:
     k╒     #  Push a list in the range [1, input-integer) again
       #    #  Take the current prime to the power of each value in this list
        ─   # After the map, flatten the list of lists
         ╧  # And check if this list contains the (implicit) input-integer
            # (after which the entire stack joined together is output implicitly)

```
> 2 votes

# Answer
# Japt, 6 bytes

I feel like this should be 1 or 2 bytes shorter ...

```
k ä¶ ×

```

Try it \- includes all test cases
> 2 votes

# Answer
# Jelly, 3 bytes

```
ÆfE

```

Try it online!
> 2 votes

# Answer
# APL (Dyalog Unicode), 8 bytes

```
∨/1~⍨⊢∨⍳

```

Try it online!

Outputs 1 if it isn't almost-prime, some other positive integer otherwise.

```
∨/1~⍨⊢∨⍳
     ⊢∨⍳   ⍝ All divisors
  1~⍨     ⍝ Remove 1
∨/         ⍝ GCD

```
> 2 votes

# Answer
# Pyt, 4 bytes

```
ϼŁ1=

```

Try it online!

```
ϼ         Implicit input; get unique ϼrime factors
 Ł        Łength of array
  1=      equals 1?; implicit print

```
> 2 votes

# Answer
# Vyxal, ~~18 16 13~~ 11 bytes

*Thanks to The Thonnu for -7 bytes*

```
ƛ?$Ḋ$æ∧;∑1=

```

Run it

Explanation:

```
ƛ      ;    # map over the input with this code:
 ?          # get input
  $         # swap
   Ḋ        # divisible?
    $       # swap
     æ      # is the item prime?
      ∧     # logical and

        ∑   # sum
         1= # is 1?

```
> 2 votes

# Answer
# Sidef, 19 bytes

```
f={.is_prime_power}

```

Try it online!
> 2 votes

# Answer
# Burlesque, 6 bytes

```
rifCsm

```

Try it online!

Explanation:

```
ri      # Read integer from input
  fC    # Find its prime factorisation
    sm  # Are all values the same?

```
> 1 votes

# Answer
# Zsh, 25 bytes

```
>`factor`
dir <->|grep \

```

Try it online!

Outputs via exit code - `1` is a prime power, `0` isn't.

* `factor` \- factorise the input
* `>``` \- create a file named each word in that output (effectively uniquifies)
* `<->` \- match any file that is just a number (eliminates the file called `input:` which comes from the output of `factor`)
* `dir` \- list those files separated by spaces (as opposed to `ls` which separates by newlines)
* `|grep \`  \- search for a space in that output (which means there were at least 2 matching files and therefore more than 1 distinct factor)
> 1 votes

# Answer
# 05AB1E, 2 bytes

```
fg

```

Try it online!

```
fg  # full program
 g  # number of...
f   # prime factors of...
    # implicit input
    # implicit output

```
> 1 votes

# Answer
# Vyxal, 1 byte

Try it Online!

Truthy outputs are `1`, falsy outputs are anything else.

# Explanation

```
† # length of prime factors

```

# Vyxal, 2 bytes

```
†ċ

```

Try it Online!

Version with distinct and consistent (albeit inverted) truthy and falsy values. A simple logical NOT `¬` could fix it for a fully correct 3 bytes: Try it Online!
> 1 votes

# Answer
# Arturo, 30 bytes

```
$=>[p:factors.prime&[]=p--p\0]

```

Try it
> 0 votes

# Answer
# PARI/GP, 5 bytes

```
ffgen

```

Attempt This Online!

A port of @Sisyphus's Sagemath answer.

Outputs via exception.

`ffgen(k)` returns a generator for the finite field of order \\$k\\$. It errors if \\$k\\$ is not a prime power.

---

# PARI/GP, 12 bytes

```
isprimepower

```

Attempt This Online!

A boring built-in.
> 0 votes

# Answer
# ForWhile, 23 bytes

`{1;[1+;;%);[';/';;%!)<}`

takes input from stack, returns `1` if number is prime power and `0` otherwise

online interpreter

# Explanation

Checks if the number has any prime factors that are larger than its smallest prime factor larger than 1.

```
 {                     }  \ anonymous procedure
  1;[1+;;%)               \ compute smallest non-trivial prime factor
  1                       \ push 1
   ;[1+;;%)               \ increase counter while it does not divide input number
           ;[';/';;%!)    \ divide number by smallest prime factor until it is no longer a factor
                      <   \ check if resulting number is less than the prime factor

```
> 0 votes

# Answer
# Ruby `-rprime`, ~~32~~ 25 bytes

Gets the prime factorization of the input and checks if it does *not* have a second element (effectively checking if the length is 1, since `n>=2` guarantees the length won't be 0).

```
->n{!n.prime_division[1]}

```

Attempt This Online!
> 0 votes

# Answer
# Thunno 2, 2 bytes

```
fạ

```

Try it online!

#### Explanation

```
fạ  # Implicit input
f   # Prime factors
 ạ  # All equal
    # Implicit output

```
> 0 votes

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