title: Generate the n'th Fermi-Dirac Prime

text:
# Question
Title: Generate the n'th Fermi-Dirac Prime
A Fermi-Dirac Prime is a prime power of the form \\$p^{2^k}\\$, where \\$p\\$ is prime and \\$k \geq 0\\$, or in other words, a prime to the power of an integer power of two. They are listed as integer sequence A050376. While a normal prime factorization generally does not contain a set of distinct primes (for example \\$24=2 \times 2 \times 2 \times 3\\$), a Fermi-Dirac prime factorization contains each Fermi-Dirac-prime at most once \\$24=2 \times 3 \times 4\\$.

Your task is to write a program that takes an integer `n` as input and prints out the `n`'th Fermi-Dirac prime or chose any other options from the standard sequence IO rules

Shortest code in bytes wins, no funny business.

**1-indexed**

```
1, 2
2, 3
3, 4
4, 5
5, 7
6, 9
7, 11
8, 13
9, 16
10, 17
100, 461
1000, 7649
6605, 65536
10000, 103919
100000, 1296749
1000000, 15476291

```

# Answer
> 5 votes
# Vyxal, ~~9~~ 8 bytes

```
ʀEĖeæa)ȯ

```

Try it Online!

Times out for numbers larger than 20. 1-indexed.

*-1 thanks to @Shaggy*

## Explained

```
ʀEĖeæa)ȯ  # takes a single integer n
      )ȯ  # first n numbers where:
ʀ         #   the range [0, that number]
 EĖe      #   to the power of 1/(2 to the power of each number in that range)
    æa    #   contains a prime number

```

# Answer
> 7 votes
# Jelly, 9 bytes

```
2Æ½Æ²¿Ẓ$#

```

A monadic Link that accepts an integer, \\$n\\$, and yields the first \\$n\\$ Fermi-Dirac primes.

**Try it online!**

### How?

```
2Æ½Æ²¿Ẓ$# - Link: integer, n
2       # - count up, starting at 2, and find the first n integers for which:
       $  -   last two links as a monad:
     ¿    -     while...
   Æ²     -     ...condition: is square?
 Æ½       -     ...action: integer square root
      Ẓ   -     is prime?

```

Note: The integer-square-root, `Æ½` could be square-root `½`, but we'd need to cast to an integer (e.g. floor, ) to use  anyway (e.g. `2.0` is not considered prime), but using `Æ½` avoids any floating point arithmetic entirely.

# Answer
> 6 votes
# Brachylog, 11 bytes (generator), 16 bytes (full program)

```
.ℕ₂ḋ=l~^h2∧

```

Try it online!

```
;I{.ḋ=l~^h2∧}ᶠ⁽b

```

Try it online!

The generator is 1-indexed. The full program outputs the first `n` prime powers, 0 indexed.

Actually not that slow.

### Explanation

```
.ℕ₂                  Output is an integer in [2,+inf)
   ḋ                 Its prime decomposition…
    =                …is a list of equal elements…
     l               …with a length…
      ~^h2∧          …being a power of 2

;I{          }ᶠ⁽      Find the first <Input> results of the following predicate:
   .ḋ                   The prime decomposition of the Output…
     =                  …is a list of equal elements…
      l                 …with a length…
       ~^h2∧            … being a power of 2
                b     Remove the first result (1, whose prime decomposition is the empty list)

```

# Answer
> 6 votes
# Python, 60 bytes

```
L={n:=1}
while{n}<=L or[print(n),L:=L|{n*l for l in L}]:n+=1

```

Attempt This Online!

Outputs indefinitely.

Complexity is exponential in N, the number of Fermi-Dirac primes to find.

## How?

Exploits the factorisation property described in OP: Maintains the set of products of each subset of the set of Fermi-Dirac primes found so far. The smallest number not in this set is the next Fermi-Dirac prime *no matter whether it happens to be a conventional prime or a power-of-2th power of one*.

# Answer
> 5 votes
# 05AB1E, 12 bytes

```
>Åp¤Ýoδm˜êNè

```

0-indexed.
Brute-force approach, so slower the larger the input is.

Try it online or verify the first 10 test cases (with `¤` replaced with `I>` to speed it up a bit, although still times out for \\$n\geq15\\$).

**Explanation:**

```
>             # Increase the (implicit) input by 1 (for edge-case n=0)
 Åp           # Pop and push a list of the first input+2 amount of prime numbers
   ¤          # Push its last/largest prime (without popping the list)
    Ý         # Pop and push a list in the range [0,max_prime]
     o        # Get 2 to the power each value in this list
      δ       # Apply double-vectorized on the two lists:
       m      #  Exponentiation
        ˜     # Flatten the list of lists
         ê    # Sorted-uniquify it
          Iè  # Get the input'th value of this list
              # (after which it is output implicitly as result)

```

# Answer
> 4 votes
# JavaScript (V8), 63 bytes

*-1 byte thanks to @jdt*

Prints the sequence indefinitely.

```
for(n=2;k=1;g(k),n++)for(g=k=>k-n?k>n||g(k*k):print(n);n%++k;);

```

Try it online!

### Commented

```
for(             // infinite outer loop:
  n = 2;         //   start with n = 2
  k = 1;         //   start each iteration with k = 1
  g(k), n++      //   after each iteration: invoke g and increment n
)                //
  for(           //   inner loop:
    g = k =>     //     start by defining the helper function g which
                 //     tests whether n = k ** (2 ** i) for some i
    k - n ?      //     if k is not equal to n:
      k > n ||   //       abort if k is greater than n
        g(k * k) //       otherwise, do a recursive call with k²
    :            //     else:
      print(n);  //       success --> print n
    n % ++k;     //     increment k until it divides n
  );             //   end of inner loop
                 // implicit end of outer loop

```

# Answer
> 4 votes
# Charcoal, ~~42~~ 26 bytes

```
≔¹θ⊞υθＦＮ«Ｗ№υθ≦⊕θ≔⁺υ×υθυ⟦Ｉθ

```

Try it online! Link is to verbose version of code. Outputs the first `n` Fermi-Dirac primes. Explanation: Now a port of @loopywalt's Python answer.

```
≔¹θ⊞υθ

```

Start with a list of `[1]`.

```
ＦＮ«

```

Repeat `n` times.

```
Ｗ№υθ≦⊕θ

```

Find the smallest positive integer not already in the list, which is the next Fermi-Dirac prime.

```
≔⁺υ×υθυ

```

Multiply all of the elements of the list by the prime and append them to the list.

```
⟦Ｉθ

```

Output the prime on its own line.

# Answer
> 4 votes
# Haskell, ~~78~~ 51 bytes

```
(2![1]!!)
n!l|elem n l=(n+1)!l|k<-l++map(*n)l=n:2!k

```

Try it online!

* saved 27 Bytes using @loopy walt approach.

Outputs n-th 0-indexed element

# Answer
> 3 votes
# Retina, 76 bytes

```
K`
"$+"{`$
_
)/^(()(((?<-2>)|\4_)\4_)+\4_(?=\4__$))*(?!(__+)\5+$)__/^+`$
_
_

```

Try it online! No test cases because of the way the program uses history. Explanation:

```
K`

```

Clear the working area.

```
"$+"{`
)`

```

Repeat `n` times.

```
$
_

```

Increment the working area.

```
/^(()(((?<-2>)|\4_)\4_)+\4_(?=\4__$))*(?!(__+)\5+$)__/^+`

```

While the working area is not a Fermi-Dirac prime...

```
$
_

```

Increment the working area.

```
_

```

Convert to decimal.

Explanation of the test:

```
()(((?<-2>)|\4_)\4_)+\4_(?=\4__$)

```

Take the square root. A test for the square root is `((^_|__\2)+)$` but the square root is held in `$#1` which is inconvenient, so instead of summing odd numbers this sums pairs of consecutive integers, and the test is not repeatable, even with the adjusted version `((?(1)\1__|_))+` that can be used within a larger expression, so it is necessary to set a dummy group with `()` and then use `(?<-2>)` to consume it on the first pass through the main loop. The last loop iteration is unrolled to allow the remainder of the value to be the square root to satisfy either the next iteration of the square root loop or the primality test.

```
(...)*

```

Take the square root as many times as possible. (Although obviously this is necessary anyway for the final root to be prime.)

```
(?!(__+)\5+$)

```

Test that the remainder is not composite.

```
__

```

Test that the remainder is at least `2`.

# Answer
> 3 votes
# sclin, 45 bytes

```
$W2+"."fltr
P/"len1="Q rev >A0:1:2log"I"Q = &

```

Try it here! Returns an infinite list. Feels very golfable...

For testing purposes (use `-i` flag if running locally):

```
; 100tk >A
$W2+"."fltr
P/"len1="Q rev >A0:1:2log"I"Q = &

```

## Explanation

Prettified code:

```
$W2+ \; fltr
  P/ ( len 1= ) Q rev >A 0:1: 2log \I Q = &

```
* `$W2+ \; fltr` filter range \[2, ∞)...
    + `P/` prime factor
        - results in frequency map `{prime => frequency}`
    + `( len 1= ) Q rev` duplicate, check if frequency map has only one prime, swap to save for later
    + `>A 0:1:` get frequency
        - i.e. get value from 0th key-value pair
    + `2log \I Q =` check if power of 2
        - i.e. check if log base 2 of the frequency is an integer
    + `&` AND

# Answer
> 2 votes
# PARI/GP 53 bytes

```
k=1;while(n,n-=2^#binary(j=isprimepower(k++))==j*2);k

```

1-indexed; given n, returns n-th Fermi-Dirac prime.

Revised version uses M.F. Hasler's is\_A050376(n) provided in OEIS A050376.

# Answer
> 2 votes
# Pip, ~~49~~ ~~33~~ 32 bytes

*-16 bytes thanks to DLosc's suggestions*

```
Wa{Yx:UoT(RT:x)%1Yxa-:1=0Ny%,y}o

```

Try It Online!

Ok I swear, the prime checking part of the code wasn't working before without the increment `U`, but now I test it again and it works?!?! Whatever, it's -1 byte.

# Answer
> 2 votes
# Raku, 40 bytes

```
grep {is-prime any $_,*.sqrt...*%1},2..*

```

Try it online!

This is probably not the best approach but whatever. Outputs as an infinite sequence.

# Answer
> 2 votes
# Wolfram Language(Mathematica), ~~94~~ 81 bytes

Saved 13 bytes thanks to the comment of @lesobrod

---

This sequence is A050376

81 bytes. Try it online!

```
(k=1;Union@@Reap[While[(m=#^(1/k))>2,Sow[Prime@Range@PrimePi@m^k];k=2k]][[2,1]])&

```

# Answer
> 0 votes
# Wolfram Language (Mathematica), 58 bytes

```
(a={x=2};Do[While@Mod[Times@@a,++x]==0;AppendTo[a,x],#];a)&

```

Try it online!

Print given number of sequence members.
Based on the next statement from Wiki:

> Another way of defining this sequence is that each element is the smallest positive integer that does not divide the product of all of the previous elements of the sequence.

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


title: Is my triangle right?

text:
# Question
Title: Is my triangle right?
Given `a, b, c` the length of the three sides of a triangle, say if the triangle is **right-angled** (i.e. has one angle equal to 90 degrees) or not.

## Input

Three **positive** integer values **in any order**

## Output

Either a specific true output (`true`, `1`, `yes`, ...) or a specific false output (`false`, `0`, `no`, ...)

## Example

```
5, 3, 4        --> yes
3, 5, 4        --> yes
12, 37, 35     --> yes
21, 38, 50     --> no
210, 308, 250  --> no

```

## Rules

* The input and output can be given in any convenient format.
* In your submission, please state the true and the false values.
* No need to handle **negative** values or **invalid edge** triple
* Either a full program or a function are acceptable. If a function, you can return the output rather than printing it.
* If possible, please include a link to an online testing environment so other people can try out your code!
* Standard loopholes are forbidden.
* This is so all usual golfing rules apply, and the shortest code (in bytes) wins.

# Answer
# Jelly, 5 bytes

```
²µSHe

```

Try it online!

Technical note: Bytes are counted in Jelly codepage.

Explanation:

```
²µSHe  Main link.
²      Square each number.
 µ     With the new list,
  S    calculate its sum,
   H   and halve it.
    e  Check if the result exists in the new list (squared input)

```

The problem is equivalent to being given three numbers `a, b, c`, and asking if there is a permutation such that `a² + b² = c²`. This is equivalent to whether `(a² + b² + c²) ÷ 2` is one of `a², b² or c²`, so the program just checks that.
> 38 votes

# Answer
# Python 2, 37 bytes

```
a,b,c=sorted(input())
1/(a*a+b*b-c*c)

```

Try it online!

-2 thanks to FlipTack.
-1 thanks to Craig Gidney.

Outputs via exit code (`0` = false, `1` = true).
> 21 votes

# Answer
# Java 8, 44 bytes

```
(a,b,c)->(a*=a)+(b*=b)==(c*=c)|a+c==b|b+c==a

```

**Explanation:**

Try it here.

```
(a,b,c)->                // Method with three integer parameters and boolean return-type
  (a*=a)+(b*=b)==(c*=c)  //  Return if `a*a + b*b == c*c`
  |a+c==b                //  or `a*a + c*c == b*b`
  |b+c==a                //  or `b*b + c*c == a*a`
                         // End of method (implicit / single-line return-statement)

```
> 17 votes

# Answer
# Python 3, 37 bytes

```
lambda*l:sum(x*x/2for x in l)**.5in l

```

Try it online!

Might run into float precision issues with large inputs.
> 13 votes

# Answer
# JavaScript (ES6), ~~43~~ ~~41~~ 40 bytes

*Saved 1 byte and fixed a bug thanks to @Neil*

Takes input as an array of 3 integers. Returns `true` for right-angled and `false` otherwise.

```
a=>a.some(n=>Math.hypot(...a,...a)==n*2)

```

```
let f =

a=>a.some(n=>Math.hypot(...a,...a)==n*2)

console.log(f([5, 3, 4     ])) //  --> yes
console.log(f([3, 5, 4     ])) //  --> yes
console.log(f([12, 37, 35  ])) //  --> yes
console.log(f([21, 38, 5   ])) //  --> no
console.log(f([210, 308, 15])) //  --> no
```

---

# Original version, 44 bytes

Takes input as 3 integers. Returns `1` for right-angled and `0` otherwise.

```
(a,b,c)=>(a*=a)+(b*=b)==(c*=c)|a+c==b|b+c==a

```

### Test cases

```
let f =

(a,b,c)=>(a*=a)+(b*=b)==(c*=c)|a+c==b|b+c==a

console.log(f(5, 3, 4     )) //  --> yes
console.log(f(3, 5, 4     )) //  --> yes
console.log(f(12, 37, 35  )) //  --> yes
console.log(f(21, 38, 5   )) //  --> no
console.log(f(210, 308, 15)) //  --> no
```
> 12 votes

# Answer
# Triangular, 57 bytes

I haven't seen any in this language yet and it seemed appropriate to try and do one. It took a bit ... as I had to get my head around it first and I believe this could be golfed some more.

```
,$\:$:*/%*$"`=P:pp.0"*>/>-`:S!>/U+<U"g+..>p`S:U/U"p`!g<>/

```

Try it online!

This expands to the following triangle.

```
          ,
         $ \
        : $ :
       * / % *
      $ " ` = P
     : p p . 0 "
    * > / > - ` :
   S ! > / U + < U
  " g + . . > p ` S
 : U / U " p ` ! g <
> /

```

The path is quite convoluted, but I'll try and explain what I have done. I will skip the directional pointers. Most of the code is stack manipulation.

* `$:*` Square the first input.
* `$:*` Square the second input.
* `S":Ug!` Test if the second value is greater than the first.
    + ***true*** `p"` Swap with the first.
    + ***false*** `p` Do Nothing.
* `$:*` Square the third input.
* `P":USg!` Test if the third value is greater than the greatest of the previous.
    + ***true*** `p+U-` sum the current stack and take away stored third value
    + ***false*** `p"U+-` sum the least and stored third and subtract from greatest
* `0=%` test equality to zero and output result.
> 8 votes

# Answer
# , 31 ~~26~~ ~~30~~ bytes

```
cat(sum(a<-scan()^2)/max(a)==2)

```

I don't like this one as much, but it is shorter. Sums the squares and divides by the largest square. Truthy if 2.

***Previous Version (modified with cat and with @Guiseppe's tip)***

```
cat(!sort(scan())^2%*%c(1,1,-1))

```

Do a sum of the sorted input with the last item negated and return the `!` not.

Try it online!
> 6 votes

# Answer
# Haskell (33 32 31 bytes)

```
(\x->(sum x)/2`elem`x).map(^2)

```

Original version:

```
(\x->2*maximum x==sum x).map(^2)

```

Anonymous function. Takes a list in the form \[a,b,c\]. Outputs True or False.

First version checked if the sum of the squares was twice the square of the maximum.

Second, slightly better version checks if half the sum of squares is an element in the list of squares.

Edit: Accidentally counted a newline, thanks H.PWiz
> 6 votes

# Answer
# Perl 6, 24 bytes

```
{(*²+*²==*²)(|.sort)}

```

Try it online!

`*²+*²==*²` is an anonymous function that returns true if the sum of the squares of its first two arguments is equal to the square of its third argument. We pass the sorted input list to this function, flattening it into the argument list with `|`.
> 6 votes

# Answer
# Brain-Flak, 68 bytes

```
({({({})({}[()])}{}<>)<>})<>({<(({}){}<>[({})])>(){[()](<{}>)}{}<>})

```

Try it online!

Uses the observation in user202729's answer.

```
 {                      }      for each input number
   {({})({}[()])}{}            compute the square
  (                <>)<>       push onto second stack
(                        )     push sum of squares onto first stack
                          <>   move to second stack

 {                                    }    for each square
   (({}){}<>[({})])                        compute 2 * this square - sum of squares
  <                >(){[()](<{}>)}{}<>     evaluate loop iteration as 1 iff equal
(                                      )   push 1 if any squares matched, 0 otherwise

```
> 6 votes

# Answer
# Python 2, 43 bytes

```
lambda a,b,c:(a*a+b*b+c*c)/2in(a*a,b*b,c*c)

```

Try it online!

# Python 2, ~~79~~ ~~70~~ ~~68~~ 62 bytes

```
lambda*l:any(A*A+B*B==C*C for A,B,C in zip(l,l[1:]+l,l[2:]+l))

```

Try it online!
> 5 votes

# Answer
# C (gcc), 49 bytes

```
n(a,b,c){return(a*=a)+(b*=b)-(c*=c)&a+c-b&b+c-a;}

```

Try it online!

Improves on Kevin Cruijssens technique

Returns 0 for a valid triangle, and a non-zero value otherwise
> 5 votes

# Answer
# C,  ~~68~~  54 bytes

Using user202729's solution.

```
f(a,b,c){return!((a*=a)+(b*=b)-(c*=c)&&a-b+c&&a-b-c);}

```

*Thanks to @Christoph for golfing 14 bytes!*

Try it online!

# C, 85 bytes

```
#define C(a,b,c)if(a*a+b*b==c*c)return 1;
f(a,b,c){C(a,b,c)C(b,c,a)C(c,a,b)return 0;}

```

Try it online!
> 4 votes

# Answer
# MATL, 7 bytes

```
SU&0)s=

```

Try it online!

### Explanation

Consider input `[12, 37, 35]`.

```
S     % Implicit input. Sort
      % [12, 35, 37]
U     % Square each entry
      % [144, 1225, 1369]
&0)   % Push last entry and remaining entries
      % STACK: 1369, [144, 1225]
s     % Sum of array
      % STACK: 1369, 1369
=     % Isequal? Implicit display
      % STACK: 1

```
> 4 votes

# Answer
# J, 10 bytes

*-6 bytes thanks to FrownyFrog*

```
=`+/@\:~*:

```

## original answer

```
(+/@}:={:)@/:~*:

```

`/:` sort the squares `*:`, then check if the sum of the first two `+/@}:` equals the last `{:`

Try it online!
> 4 votes

# Answer
# Japt, 8 bytes

```
m²ø½*Ux²

```

Try it

# Japt `-x¡`, 7 bytes

```
Ë²Ñ¶Ux²

```

Try it
> 4 votes

# Answer
# Julia 0.6, 16 bytes

```
!x=x⋅x∈2x.*x

```

Try it online!

### How it works

Let **x = \[a, b, c\]**.

`x⋅x` is the dot product of **x** and itself, so it yields **a² + b² + c²**.

`2x.*x` is the element-wise product of **2x** and **x**, so it yields **\[2a², 2b², 2c²\]**.

Finally,  tests if the integer **a² + b² + c²** belongs to the vector **\[2a², 2b², 2c²\]**, which is true iff
**a² + b² + c² = 2a²** or **a² + b² + c² = 2b²** or **a² + b² + c² = 2c²**, which itself is true iff
**b² + c² = a²** or **a² + c² = b²** or **a² + b² = c²**.
> 4 votes

# Answer
# Triangularity,  ~~49~~  31 bytes

```
...)...
..IEO..
.M)2s^.
}Re+=..

```

Try it online!

### Explanation

Every Triangularity program must have a triangular padding (excuse the pun). That is, the **i**th line counting from the bottom of the program must be padded with **i - 1** dots (`.`) on each side. In order to keep the dot-triangles symmetrical and aesthetically pleasant, each line must consist of **2L - 1** characters, where **L** is the number of lines in the program. Removing the characters that make up for the necessary padding, here is how the code works:

```
)IEOM)2s^}Re+=     Full program. Input: STDIN, Output: STDOUT, either 1 or 0.
)                  Pushes a zero onto the stack.
 IE                Evaluates the input at that index.
   O               Sorts the ToS (Top of the Stack).
    M)2s^}         Runs the block )2s^ on a separate stack, thus squaring each.
          R        Reverse.
           e       Dump the contents separately onto the stack.
            +      Add the top two items.
             =     Check if their sum is equal to the other entry on the stack (c^2).

```

Checking if a triangle is right-angled in Triangularity...
> 4 votes

# Answer
# Java (OpenJDK 8), 68 bytes

```
a->{java.util.Arrays.sort(a);return a[0]*a[0]+a[1]*a[1]==a[2]*a[2];}

```

Try it online!
> 3 votes

# Answer
# PowerShell, 39 bytes

```
$a,$b,$c=$args|sort;$a*$a+$b*$b-eq$c*$c

```

Try it online!

Sorts the input, stores that into `$a,$b,$c` variables. Then uses Pythagorean theorem to check whether `a*a + b*b = c*c`. Output is either Boolean `True` or `False`.
> 3 votes

# Answer
# 05AB1E, 6 bytes

```
n{R`+Q

```

Try it online!
> 3 votes

# Answer
# Perl 5, 34 +2 (-ap) bytes

```
$x+=($_*=$_)/2for@F;$_=grep/$x/,@F

```

seems that can be shortened to 29 +2 but there is a warning: smartmatch is experimental

```
$x+=($_*=$_)/2for@F;$_=$x~~@F

```

the question i couldn't prove but it works in all tests i've tried is if the number (a^2+b^2+c^2)/2 can be a substring of a number (a^2/2 b^2/2 or c^2/2) which would give a false positive.

Try It Online
> 3 votes

# Answer
# Ohm v2, ~~8~~ 6 bytes

```
²DS)Σε

```

Try it online!
> 3 votes

# Answer
# Racket, ~~64~~ 60 bytes

```
(λ(a b c)(=(+(* a a)(* b b)(* c c))(*(expt(max a b c)2)2)))

```

Try it online!

### How it works

Tests if `a^2 + b^2 + c^2` is equal to twice the largest of `a^2`, `b^2`, and `c^2`.

Returns `#t` for right triangles and `#f` for all other inputs.

---

* *-4 bytes thanks to @xnor's suggestion to use `expt`.*
> 3 votes

# Answer
# Gaia, 6 bytes

```
s¦ΣḥuĖ

```

Try it online!

* \- **s**quare each.
* `Σ` \- sum.
* \- alve.
* `u` \- sq**u**are root.
* `Ė` \- contains? Check if the square root is in the input.
> 3 votes

# Answer
# RProgN 2, 10 bytes

```
§²2^r]‘\+e

```

## Explained

```
§²2^r]‘\+e
§           # Sort the input list
 ²2^r       # Square each element in the list.
     ]      # Duplicate it on the reg stack.
      ‘     # Pop the top (largest) element off it
       \+   # Swap it, sum the rest of the list.
         e  # Are they equal?

```

Try it online!
> 3 votes

# Answer
# Pari/GP, ~~29~~ 24 bytes

```
f(v)=v~==2*vecmax(v)^2

```

Try it online!

Saved five bytes by an obvious change from `norml2(v)` to `v*v~`.

Inspired by other answers.

Here `v` must be a row vector ~~or a column vector~~ with three coordinates.

Example of use: `f([3,4,5])`

Of course, you get rational side lengths for free, for example `f([29/6, 10/3, 7/2])`.

If I do not count the `f(v)=` part, that is 19 bytes. The first part can also be written `v->` (total 22 bytes).

**Explanation:** If the three coordinates of `v` are `x`, `y` and `z`, then the product of `v` and its transpose `v~` gives a scalar `x^2+y^2+^z^2`, and we need to check if that is equal to twice the square of the maximum of the coordinates `x`, `y`, `z`.

**Extra:** The same `f` tests for a Pythagorean quadruple if your input vector has four coordinates, and so on.
> 3 votes

# Answer
# TI-Basic, ~~13~~ ~~11~~ 10 bytes

```
max(Ans=R►Pr(min(Ans),median(Ans

```

Now works for inputs in any order and is shorter as well. Another -1 thanks to @MishaLavrov
> 3 votes

# Answer
# Ruby, 31 bytes

```
->a{a,b,c=*a.sort;a*a+b*b==c*c}

```

Takes input as a list of 3 integers. Uses some ideas from other solutions.
> 3 votes

# Answer
# CJam, 9

```
q~$W%~mh=

```

Try it online

**Explanation:**

```
q~      read and evaluate the input (given as an array)
$W%     sort and reverse the array
~       dump the array on the stack
mh      get the hypotenuse of a right triangle with the given 2 short sides
=       compare with the longer side

```
> 3 votes

# Answer
# Common Lisp, 64 bytes

```
(apply(lambda(x y z)(=(+(* x x)(* y y))(* z z)))(sort(read)#'<))

```

Try it online!

As usual in Common Lisp, true is `T` and false is `NIL`.
> 3 votes

# Answer
# MS Excel, 48 Bytes

Anonymous worksheet function that takes input from the range \[A1:C1\] and outputs to the calling cell.

```
=Let(a,A1^2,b,B1^2,c,C1^2,Or(a+b=c,b+c=a,a+c=b))

```
> 3 votes

# Answer
# JavaScript 6, recursive way, 40 Bytes

```
f=(a,b,c)=>c<a|c<b?f(b,c,a):a*a+b*b==c*c

```

```
f=(a,b,c)=>c<a|c<b?f(b,c,a):a*a+b*b==c*c
console.log(f(4,5,3));
console.log(f(4,5,6));
```

# C (gcc), 42 bytes

```
f(a,b,c){c=c<a|c<b?f(b,c,a):a*a+b*b==c*c;}

```

Try it online!
> 3 votes

# Answer
# Excel, 47 bytes

Returns `FALSE` for right-angled Triangles, else `TRUE`:

```
=ISERR(FIND(SQRT((A1^2+B1^2+C1^2)/2),A1&B1&C1))

```
> 3 votes

# Answer
# Proton, 31 bytes

```
k=>(sum(j*j for j:k)/2)**.5in k

```

Try it online!

Credit to user202729 for the idea go upvote them
> 2 votes

# Answer
# Neim, 6 bytes

```
ᛦDᚺS

```

Try it online!
> 2 votes

# Answer
# Dyalog APL, ~~17~~ 16 bytes

```
{(+/2÷⍨⍵*2)∊⍵*2}

```

Try it!

Outputs 1 for true, 0 for false.

Thanks to @Adám for 1 byte.

### How it works

```
{(+/2÷⍨⍵*2)∊⍵*2}          # Anonymous function
 (     ⍵*2)               # Each input (⍵) to the 2nd power
    2÷⍨                   # divided by 2
  +/                      # Sum
           ∊              # "is in"
            ⍵*2           # Each input (⍵) to the 2nd power

```

This uses the same logic as @user202729's Jelly answer, so some credit goes to them.
> 2 votes

# Answer
# Swift 3, 81 bytes

```
func r(v:[Int]){let a=v.sorted{$0<$1};print("\(a[0]*a[0]+a[1]*a[1]==a[2]*a[2])")}

```
> 2 votes

# Answer
## Batch, 61 bytes

```
@cmd/cset/ax=%1*%1,y=%2*%2,z=%3*%3,!((x+y-z)*(y+z-x)*(z+x-y))

```

Outputs `1` or `0` appropriately.
> 2 votes

# Answer
# Pyth, 14 bytes

```
K_m*ddSQqstKhK

```

Try it online!
> 2 votes

# Answer
# Tcl, 70 bytes

```
proc R {a b c} {expr $a[set H ==hypot(]$b,$c)||$b$H$a,$c)||$c$H$a,$b)}

```

Try it online!

Still too long.
> 2 votes

# Answer
# Eukleides, 81 bytes

```
x=number("")^2;y=number("")^2;z=number("")^2
print x==y+z or y==x+z or z==y+x?1|0

```

I thought Eukleides would handle this nicely using geometric builtins, but this actually turned out to be longer than just testing against the Pythagorean theorem, because the right triangle assertion is picky about order, and we have to turn our sides into a triangle first:

```
d e f triangle number(""),number(""),number("")
print right(d,e,f)or right(e,f,d)or right(f,d,e)?1|0

```

...which is 100 bytes. One nice thing about that one is it'll error out given an impossible triangle. Anyway, for either one, input is via STDIN, output is 1 for right, 0 for non-right via STDOUT. Doing a function was actually longer in this instance.
> 2 votes

# Answer
# Pyth, ~~11~~ 10 bytes

```
}/sK^R2Q2K

```

Try it online!

My first Pyth submission! Explanation:

```
     R        right map
    ^ 2       squaring
       Q      of the input
   K          save this in K
  s           sum up
 /      2     divide by 2
}        K    test if this sum is in K

```

saved a byte thanks to Mr. Xcoder
> 2 votes

# Answer
# C++, 156 bytes

```
bool f(int*a){int g=[](int*b){return b[0]>b[1]?b[0]>b[2]?0:2:b[1]>b[2]?1:2;}(a);int c[2]={g?0:1,g>1?1:2};return pow(a[c[0]],2)+pow(a[c[1]],2)==pow(a[g],2);}

```
> 2 votes

# Answer
# Racket, 109 bytes

```
#lang racket/base
(define (isright a b c)
  (if (equal? (+ (* a a) (* b b)) (* c c))
      "yes"
      "no"))

```

Try it online!
> 2 votes

# Answer
# Dyalog APL, 12 bytes

```
(+/2÷⍨×⍨)∊×⍨

```

Uses the same method as this Jelly answer.

Try it online!
> 2 votes

# Answer
# MY, 13 bytes

```
22ω^÷Σ2ω^=Σ←

```

Try it online!

This helped me realize ... I screwed up the NOT function (and the boolean conversion function).

## How it works (cross-compatible function)

```
22ω^÷Σ2ω^=Σ←
2             = push 2 to the stack
 2ω^          = push ω^2 to the stack (functions vectorize)
    ÷         = pop a, then b. push a/b (rational) to the stack
     Σ        = sum
      2ω^=    = equality test with ω^2
          Σ  = boolean conversion
            ← = output

```
> 2 votes

# Answer
## CJam 10

```
q~$_.*~-+!

```

Simplest one I found but also shortest

```
q reads input as string. Leave input formatted as array [3 4 5]
~ dumps it to stack
$ sorts array
_ duplicates array
.* multiplies each element by itself
~ dumps array to stack
-+ determines largest minus two smallest numbers
! if 0 return 1 and 0 if anything else

```

Try it online
> 2 votes

# Answer
# Go, ~~96~~ 94 bytes

```
package r;import"sort";func I(i...int)bool{sort.Ints(i);return i[0]*i[0]+i[1]*i[1]==i[2]*i[2]}

```

Test:

```
import "r"
import "fmt"

func main() {
    fmt.Println(r.I(3, 5, 4))
    fmt.Println(r.I(12, 37, 35))
    fmt.Println(r.I(21, 38, 5))
    fmt.Println(r.I(210, 308, 15))
}

```

Try it online!
> 2 votes

# Answer
# Jq 1.5, ~~31~~ 23 bytes

```
map(.*.)|.[[add/2]]!=[]

```

Expects input in form of 3 element array, e.g. `[5, 3, 4]`

Expanded

```
  map(.*.)           # square each element
| .[[ add/2 ]]!=[]   # true if index of sum/2 element exists

```

Thanks to mdahmoune for suggesting shorter approach then my original one.

Try it online!

---

# Jq 1.5, 31 bytes

```
sort|map(.*.)|(.[:2]|add)==.[2]

```

Expects input in form of 3 element array, e.g. `[5, 3, 4]`

Expanded

```
  sort                   # put elements in order
| map(.*.)               # square each element
| (.[:2]|add) == .[2]    # is sum of first two equal to third?

```

Try it online!
> 2 votes

# Answer
# APL (Dyalog), 10 bytes

```
(+/∊×∘2)×⍨

```

Try it online!

`×⍨` square (lit. multiplication selfie)

`(``)` apply the following anonymous tacit function on that:

`+/` the sum

is a member of

`×∘2` the doubled amounts
> 2 votes

# Answer
Two answers found by refining the answer by Steadybox and incorporating the technique in the Java answer by Kevin Cruijssen:

# C, 52 bytes

```
f(a,b,c){return(a*=a)+(b*=b)==(c*=c)|b+c==a|c+a==b;}

```

# C, 74 bytes

```
#define _(a,b,c)a*a+b*b==c*c||
f(a,b,c){return _(a,b,c)_(b,c,a)_(c,a,b)0;}

```

# Test program

```
#include <stdio.h>
int test(int a, int b, int c, int expected)
{
    int actual = f(a,b,c);
    if (expected != actual) {
        fprintf(stderr, "%d %d %d => %d\n ", a,b,c, actual);
        return 1;
    }
    return 0;
}

int main()
{
    return test(5, 3, 4, 1)
        +  test(3, 5, 4, 1)
        +  test(12, 37, 35, 1)
        +  test(21, 38, 50, 0)
        +  test(210, 308, 250, 0)
        ;
}

```
> 2 votes

# Answer
# Pushy, ~~10~~ 8 bytes

```
GK2ek+=#

```

**Try it online!**

Managed to cut off two bytes by changing the approach, here's how it works now:

```
          \ Implicit Input                  eg. [3, 4, 5]
G         \ Sort the stack descendingly         [5, 4, 3]
 K2e      \ Square all items                    [25, 16, 9]
    k+    \ Sum last two                        [25, 25]
      =   \ Check equality (1 or 0)             [1]
       #  \ Output result                       PRINT: 1

```

## Original Version, 10 bytes

```
gK2eSk2/=#

           \ Input implicitly on stack.              eg. [5, 4, 3]
 g         \ Sort the stack ascendingly.                 [3, 4, 5]
 K2e       \ Square all items.                           [9, 16, 25]
 Sk2/      \ Append stack sum divided by 2               [9, 16, 25, 25]
 =#        \ Print equality of last two items (1/0)      PRINT: 1

```
> 2 votes

# Answer
# Swift 4, 68 bytes

```
func f(v:inout[Int]){v.sort();print(v[0]*v[0]+v[1]*v[1]==v[2]*v[2])}

```

Accepts a mutable array as inout argument and prints `true` or `false`.

Swift Sandbox.
> 2 votes

# Answer
# Octave, 29 bytes

```
sum(a=input("").^2)==max(2*a)

```

Try it online!

Input has to be given in a format octave understands as a vector, like `[3 5 4]` or `[12;35;37]`.

Checks for Pythagoras's theorem: first, square all the sides, then check if the sum of squares of all the sides is twice the square of the hypotenuse.

Output will be either `ans = 1` or `ans = 0`
> 2 votes

# Answer
## C# (53)

The shortest possible code I could find was the one that looks like the JAVA solution:

```
(a,b,c)=>{return(a*=a)+(b*=b)==(c*=c)|a+c==b|b+c==a;}

```

Try it online

## Array-input (58)

```
a=>{Array.Sort(a);return a[0]*a[0]+a[1]*a[1]==a[2]*a[2];};

```
> 2 votes

# Answer
# Add++, ~~25~~ 18 bytes

```
D,f,?,caaBcB*#s/2=

```

Try it online!

-7 bytes thanks to mdahmoune

<sub>Yes, I got outgolfed in my own language by 7 bytes. So what?</sub>

## How does it work?

```
D,f,?,      - Create a variadic function, f. Example arguments: [5 3 4]
      c     - Clear the stack;      STACK = []
      a     - Push the arguments;   STACK = [[5 3 4]]
      a     - Push the arguments;   STACK = [[5 3 4] [5 3 4]]
      Bc    - Push the columns;     STACK = [[5 5] [3 3] [4 4]]
      B*    - Product of each;      STACK = [25 9 16]
      #     - Sort the stack;       STACK = [9 16 25]
      s     - Push the sum;         STACK = [9 16 25 50]
      /     - Divide;               STACK = [9 16 2]
      2     - Push 2;               STACK = [9 16 2 2]
      =     - Equal;                STACK = [9 16 1]

```

Implicitly return the top element on the stack

## Old version

```
D,f,?,c2 2 2B]a@BcB`#s/2=

```

The only difference is the squaring of each element (`aaBcB*` in the golfed version, `2 2 2B]a@BcB`` in this version), so I'll quickly explain how this part works

```
              - Stack is currently empty
2 2 2         - Push 2 three times;             STACK = [2 2 2]
     B]       - Wrap the stack in an array;     STACK = [[2 2 2]]
       a      - Push the arguments as an array; STACK = [[2 2 2] [5 3 4]]
        @     - Reverse the stack;              STACK = [[5 3 4] [2 2 2]]
         Bc   - Push the columns of the stack;  STACK = [[5 2] [3 2] [4 2]]
           B` - Reduce each by exponentiation;  STACK = [25 9 16]

```
> 2 votes

# Answer
## CJam, ~~12~~ 11 bytes

This is depressingly long.

```
{$2f#)\:+=}

```

Try it online!

Anonymous block that takes input as an array of integers on the stack and returns `1` (truthy) or `0` (falsey).

Explanation:

```
{      e# Stack:        [12 37 35]
 $     e# Sort:         [12 35 37]
 2f#   e# Square each:  [144 1225 1369]
 )     e# Pop:          [144 1225] 1369
 \     e# Swap:         1369 [144 1225]
 :+    e# Sum:          1369 1369
 =     e# Equal:        1
}      e# Result: 1 (truthy)

```

### Old solution

```
{2f#_:+2/#)}

```

Try it online!

Anonymous block that takes an array of integers on the stack and returns a truthy or falsy integer.
> 2 votes

# Answer
# Stacked, 18 bytes

```
[sorted:*rev...+=]

```

Try it online!

## Explanation

This is an anonymous function that takes an array of three integers. It sorts (`sorted`), squares each element of the array (`:*`), and reverses the array with `rev`. This will give an array with the largest value in the front. `...` pushes each individual member of the array onto the stack, which would make the stack look like:

```
c^2  b^2  a^2

```

`+` addes the top two members, yielding:

```
c^2  (b^2+a^2)

```

`=` tests for equality. yielding the expression `a^2 + b^2 == c^2`, which is only true for right triangles.
> 2 votes

# Answer
## GNUOctave, 32 bytes

```
A=input("")
sum(A.^2)/2==max(A)^2

```

The input must be like : `[1,2,3]` so Octave can evaluate it to a Matrix.

`A.^2` squares all the elements of the matrix.

Outputs 1 if the triangle is right-angled, 0 otherwise.

You can try it online : https://octave-online.net

**Edit (27 bytes):** I saw this answer I thought I could find a better solution. I took the idea of squaring the matrix at the beginning. I don't feel like this deserves upvotes since it wasn't really my whole idea to begin with.

```
A=input("").^2
sum(A)/max(A)

```

Outputs 2 if the triangle is right-angled and anything else if it isn't.
> 2 votes

# Answer
# Axiom, 39 bytes

```
f x==(y:=sort x;y.1^2+y.2^2=y.3^2=>1;0)

```

f(x) function Input one list of at last 3 numbers

Output 1 (it is right triangle)

Output 0 (it is not right triangle)
> 2 votes

# Answer
# Pyt, ~~12~~ ~~8~~ 6 bytes

```
²ĐƩ₂⇹∈

```

Explanation:

```
                 implicit input (as a list, i.e., "[A,B,C]")
 ²               square each element in the list
  Đ              duplicate the list (on stack twice)
   Ʃ             sum elements in list on top of stack
    ₂            divide sum by 2
     ⇹           swap top two items on stack
      ∈          check if sum/2 is in the list of squares
                 implicit print

```

Try it online!
> 2 votes

# Answer
# GolfScript, 10 bytes

```
~${.*}/-+!

```

Try it online!

Takes an array as input and outputs 1 for true and 0 for false.

```
~$           # Sort the array                  [3 4 5]       [1 2 3]
  {.*}/      # Square all elements             9 16 25       1 4 9
       -     # Subtract the last two numbers   9 -9          1 -5
        +    # Add the numbers left            0             -4
         !   # Negate the answer               1             0

```
> 2 votes

# Answer
# Wolfram Language (Mathematica), ~~18~~ 14 bytes

```
#.#==2Max@#^2&

```

Try it online!

Thanks to @att for –4 bytes!

Checks if the sum of the squared numbers is equal to twice the square of the maximum number.
> 2 votes

# Answer
# Templates Considered Harmful, 140 bytes

```
Fun<Ap<Fun<bor<Eq<Add<A<1>,A<2>>,A<3>>,bor<Eq<Add<A<2>,A<3>>,A<1>>,Eq<Add<A<3>,A<1>>,A<2>>>>>,Mul<A<1>,A<1>>,Mul<A<2>,A<2>>,Mul<A<3>,A<3>>>>

```

Try it online!

Anonymous function (all TCH functions are anonymous) that takes 3 integers as inputs.

Cool language that uses C++ templates evaluated by a typedef. Interestingly, this is a similar length to the actual C++ answer.

---

```
Fun<  //Anonymous function declaration
  Ap< //Apply following function with arguments (a²,b²,c²)
    Fun<
      bor<
        Eq<Add<A<1>,A<2>>,A<3>>,  // (a²+b²=c²)|
        bor<                      //((b²+c²=a²)|
          Eq<Add<A<2>,A<3>>,A<1>>,// (c²+a²=b²))
          Eq<Add<A<3>,A<1>>,A<2>>
        >
      >
    >,
    Mul<A<1>,A<1>>,Mul<A<2>,A<2>>,Mul<A<3>,A<3>> //arguments (a²,b²,c²)
  >
>

```
> 2 votes

# Answer
# Vyxal, 35 bits<sup>v2</sup>, 4.375 bytes

```
²:∑½c

```

Try it Online!

Ports Thunno 2

## Explained (old)

```
s²Ṙḣ∑=
s²     # sort and square the input
  Ṙ    # reverse the list so that it's in descending order
   ḣ   # push the head of that, and the rest of that to the stack
    ∑= # does the sum of the list equal the other item?

```
> 2 votes

# Answer
# Mathematica 39 24 bytes

With 15 bytes saved thanks to Jenny\_mathy.

```
#^2+#2^2==#3^2&@@Sort@#&

```

---

`Sort` ensures that the diagonal will be the third element of `z`. `z[[1]]^2` means

**Example**

```
#^2+#2^2==#3^2&@@Sort@#&[{3,5,4}]

 (*True*)

```
> 1 votes

# Answer
# Lua, 66 bytes

```
function f(...)t={...}table.sort(t)print(t[1]^2+t[2]^2==t[3]^2)end

```

This could be simplified by using table call syntax which would mean that the table does not need to be constructed in the function, saving 9 bytes.

Try it online!

Try it online on tio.run!
> 1 votes

# Answer
# PHP, 48 47 bytes

```
sort($a);echo($a[2]**2==$a[1]**2+$a[0]**2)?1:0;

```

Try it online!

Outputs 1 for true, 0 for false.
> 1 votes

# Answer
# Excel VBA, 49 Bytes

Anonymous VBE immediate window function that takes input from range \[A1:C1\] and output to the VBE immediate window.

```
[2:2]=[(1:1)^2]:?[Or(A2+B2=C2,B2+C2=A2,A2+C2=B2)]

```
> 1 votes

# Answer
# Pyth \- ~~23~~ 22 Bytes, ~~22~~ 21 if falsy value doesn't need to be the same every time

```
!-+^@KSQZ2^@K1 2^@K2 2

```

Try it online!

Returns `True` or `False`

or (if falsy value does not need to be the same every time)

```
-+^@KSQZ2^@K1 2^@K2 2

```

Try it online!

Returns `0` or a number other than `0`

This can probably be golfed a lot

Explanation:

```
!        Logical negate; Makes 0 true and others false. Not necessary if falsy values can be different
 -       Subtract
  +      Add
   ^     To the power of
    @    Index in
     K   Assign variable K, returning K
      S  Sorted
       Q Input
     Z   Zero
    2    2
   ^     To the power of
    @    Index in
     K   Variable K
     1   1
    2    2
   ^     To the power of
    @    Index In
     K   Variable K
     2   2
    2    2

```
> 1 votes

# Answer
# APL NARS 14 chars

```
{⍵∊⍨√2÷⍨+/⍵*2}

```

(seen in some other answer) test:

```
  f←{⍵∊⍨√2÷⍨+/⍵*2}
  f 3 4 5
1
  f 1 1 1
0
  f 5 3 4
1
  f 3 5 4
1
  f 12 37 35
1
  f 21 38 50
0
  f 210 308 250
0

```

Here ⍵ is the argument of function f.

```
{⍵∊⍨√2÷⍨+/⍵*2}
           ⍵*2} if ⍵=1 2 3, ⍵*2 will be 1 4 9 (square the argument ⍵)
         +/     if ⍵*2 is 1 4 9 here sum it 1+4+9=14(sum list)
     √2÷⍨       here makes d=sqrt( (sum list above)/2 )
 ⍵∊⍨            here return 1 if d is element of ⍵, else return 0
                 because ⍨ reverse arguments of its left operator ∊

```

This follow from this: Given a, b, c the length of one triangle, they are the length of one right triangle \<=\> a^2+b^2=c^2 and a,b,c different from 0.

```
  |\
  | \
  |  \
 a|   \c
  |    \
  |_____\
     b
  a^2+b^2=c^2 <=> (a^2+b^2+c^2)/2=(2*a^2+2*b^2)/2=a^2+b^2=c^2 <=>
  <=> (a^2+b^2+c^2)/2 ∊ {a^2, b^2, c^2}

```
> 1 votes

# Answer
# 05AB1E, 5 bytes

```
à‚nOË

```

Try it online!
> 1 votes

# Answer
# Julia 0.6, 14 bytes

```
L->L'L∈2L.^2

```

Try it online!

Based @mdahmoune's hint that "The problem is equivalent to whether (a² + b² + c²) ÷ 2 is in {a², b², c²}" - this expresses the condition "(a² + b² + c²) is in {2a², 2b², 2c²}" for a given array `L=[a,b,c]`.

`L'L` is multiplying the array by itself as a matrix multiplication, so

```
[a b c]*[a    = a^2 + b^2 + c^2
         b
         c]

```

`L.^2` is elementwise squaring, so is equal to `[a^2 b^2 c^2]`.

is a synonym to `in`, and checks membership - so the code checks that "sum of squares evaluates to twice of any one of the squares".

Just saw @Dennis' previous Julia answer and saved a few bytes thanks to that. This golf improves on it by two bytes, by using `L'L` instead of `L⋅L` (⋅ is a 3-byte Unicode character).
> 1 votes

# Answer
# PHP, 44 bytes

```
echo($a**2+$b**2+$c**2)/2==max($a,$b,$c)**2;

```

Try it online!

Half the sum of the squares of the sides should equal the square of the max side. Emits `"1"` for true and `""` (empty string) for false.

The TIO link runs all the tests in a loop.
> 1 votes

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

```
(a,b,c)=>[a*=a,b*=b,c*=c].includes((a+b+c)/2)

```

Try it online!

Half the sum of the squares of the sides should equal the square of the max side. Returns a bool.

The TIO link runs all the tests in a loop.
> 1 votes

# Answer
# Rust, 44 bytes

```
|n|{n.sort();n[0]*n[0]+n[1]*n[1]==n[2]*n[2]}

```

Try it online! Takes in an `&mut[u64]` of at least three elements and proceeds to sort and test if the Pythagorean theorem holds. If sorting floats in rust were easier (it's hard because they can't implement the `Ord` trait, which is required by the sorting functions) I could use the `hypot` function and wind up with this:

```
|n|{n.sort();n[0].hypot(n[1])==n[2]}

```

which is much shorter.
> 1 votes

# Answer
# SmileBASIC, 55 bytes

```
DEF R(T)SORT T
RETURN SQR(T[0]*T[0]+T[1]*T[1])==T[2]END

```
> 0 votes

# Answer
# Lua, 90 bytes

```
t={...}for k,v in pairs(t)do t[k]=tonumber(v)end table.sort(t)print(t[1]^2+t[2]^2==t[3]^2)

```

Try it online!
> 0 votes

# Answer
# Japt, 7 bytes

```
øUx²z q

```

Try it online!
> 0 votes

# Answer
# Thunno 2, 5 bytes

```
²DS½Ƈ

```

Attempt This Online!

Port of DELETE\_ME's Jelly answer.

#### Explanation

```
²DS½Ƈ  # Implicit input         ->  [5, 3, 4]
²      # Square each value      ->  [25, 9, 16]
 DS    # Duplicate and sum      ->  [25, 9, 16]  50
   ½   # Halve the sum          ->  [25, 9, 16]  25
    Ƈ  # Check for containment  ->  1
       # Implicit output

```
> 0 votes

---
Tags: code-golf, math, decision-problem, geometry
---


# Question
Title: Answer to life, the universe, and everything
# Task

Given a String as input, your task is to output `42` **only** if the input String happens to be *exactly* the following :

```
abbcccddddeeeeeffffffggggggghhhhhhhhiiiiiiiiijjjjjjjjjjkkkkkkkkkkkllllllllllllmmmmmmmmmmmmmnnnnnnnnnnnnnnoooooooooooooooppppppppppppppppqqqqqqqqqqqqqqqqqrrrrrrrrrrrrrrrrrrsssssssssssssssssssttttttttttttttttttttuuuuuuuuuuuuuuuuuuuuuvvvvvvvvvvvvvvvvvvvvvvwwwwwwwwwwwwwwwwwwwwwwwxxxxxxxxxxxxxxxxxxxxxxxxyyyyyyyyyyyyyyyyyyyyyyyyyzzzzzzzzzzzzzzzzzzzzzzzzzz

```

It may output any other value, produce an error or not output at all, if the input does not equal the aforementioned String.

---

## Winning Criterion

This is , so the shortest code in bytes wins!

# Answer
## Golfscript, 20

```
26,{.97+\{.}*}%=42`*

```

with new line, 21 chars (by Nabb)

```
26,{).[96+]*}%n+=42`*

```

Actually Nabb beat mine, here is original solution for with new line, 22 chars

```
26,{.97+\{.}*}%n+=42`*

```

This is simply generating source string and just comparing it against string from stdin.
> 20 votes

# Answer
## Ruby 1.9, ~~46 42~~ 39 characters

```
p (?a..?z).map{|a|a*$.+=1}*""==gets&&42

```

Assumes the input isn't terminated with a newline.
> 13 votes

# Answer
## C program - 78 89

**Edit:** Do not print 42 when there are extra characters.

Assumes input does not have a trailing newline.

```
main(i,j){for(i=1;i<27;i++)for(j=i;j--;getchar()==96+i?0:exit(1));puts("42"+!!gets(&i));}

```

If the prefix does not match, the program exits. If the prefix matches but there is 1-3 or so extra characters, prints 2. Otherwise, produces undefined behavior.

This can be made one character shorter by changing `exit(1)` to `fork()`. Oh, and on an unrelated note, remember to save any open documents in case, for whatever reason, your system happens to lock up.
> 11 votes

# Answer
## PHP (60)

Assuming the input is provided in the commandline:

```
for(;$i<702;)$s.=chr(96.5+sqrt($i+=2));echo$s!=$argv[1]?:42;

```

**Explanation**: you can view the string as a triangle structure.

```
j     i   val
0     0   a
1   1-2   bb
2   3-5   ccc
3   6-9   dddd
4 10-14   eeeee
5 15-20   ffffff
      ...

```

Line `j` starts at index `i = j*(j+1)/2` (that's the triangular number formula). Solving the quadratic equation results in index `i` being on line `j = int((sqrt(8*i+1)-1)/2)` and therefore containing character `97 + int((sqrt(8*i+1)-1)/2)`. The `0-350` index range allows us to simplify that to `96.5 + sqrt(2*(i+1))`, but that no longer holds true for larger values.

**Edit**: Switched to commandline input as suggested in the comments.
**Edit**: Uses conditional operator to save a character
> 8 votes

# Answer
## Perl, 35 ~~43~~

```
map$s.=$_ x++$a,a..z;say 42if<>~~$s

```

Needs Perl 5.10 or later (run with `-E`), no newline in input.

I liked my side-effects regex better, but the shorter code has spoken. Here it is as a souvenir. Also intended for Perl 5.10 or later, but only for the advanced/experimental regex features, so only a `p` command-line option is needed.

```
$a=a;$_=/^(??{$b++;$a++."{$b}"}){26}$/&&42

```
> 7 votes

# Answer
# 05AB1E, 7 bytes

```
AƶJQi42

```

Try it online!

### Explanation

```
A       push lowercase alphabet
 ƶ      lift every letter, push it and multiply it by its index
  J     join the list
   Qi   does it equal the input?
     42 push 42 and output implicitly

```

Just going through some challenges to learn 05AB1E (and golfing in general). This challenge was marked as active yesterday and I found a short solution, so why not share? :)
> 7 votes

# Answer
## Haskell program - 71 67 64 57

Assumes no trailing newline, and does not output one either.

```
f x|x==[c|c<-['a'..'z'],_<-['a'..c]]="42"
main=interact f

```

Usage:

```
$ echo -n 'abbcccddddeeeeeffffffggggggghhhhhhhhiiiiiiiiijjjjjjjjjjkkkkkkkkkkkllllllllllllmmmmmmmmmmmmmnnnnnnnnnnnnnnoooooooooooooooppppppppppppppppqqqqqqqqqqqqqqqqqrrrrrrrrrrrrrrrrrrsssssssssssssssssssttttttttttttttttttttuuuuuuuuuuuuuuuuuuuuuvvvvvvvvvvvvvvvvvvvvvvwwwwwwwwwwwwwwwwwwwwwwwxxxxxxxxxxxxxxxxxxxxxxxxyyyyyyyyyyyyyyyyyyyyyyyyyzzzzzzzzzzzzzzzzzzzzzzzzzz' | { ./42; echo; }
42
$ echo -n 'something else' | { ./42; echo; }
42: 42.hs:1:0-54: Non-exhaustive patterns in function f

$

```
> 6 votes

# Answer
## J, 29

```
f=:42#~((>:#a.{~97+])i.26)-:]

```

example:

```
f 'oasijfiojasef'

f 23841235

f 'abbccc...'
42

```
> 4 votes

# Answer
# D: 94 Characters

```
void f(S)(S s){S t;foreach(i;0..26)t~=array(repeat(cast(char)(i+'a'),i+1));s==t&&writeln(42);}

```

More Legibly:

```
void f(S)(S s)
{
    S t;

    foreach(i; 0 .. 26)
        t ~= array(repeat(cast(char)(i + 'a'), i + 1));

    s == t && writeln(42);
}

```
> 4 votes

# Answer
## Delphi, 164 132

This one builds a string and just compares it against the first command-line argument. It's shorter and less tricky than my other submission :

```
var s:string;c,i:int8;begin repeat s:=s+Char(c+97);i:=i-1;c:=c+Ord(i<0);if i<0then i:=c;until c=26;Write(42*Ord(s=ParamStr(1)));end.

```

(Note, that this version assumes that the `c` and `i` variables start out initialized at 0, as is the case in my version of Delphi (2010).)

Like my other submission, this one needs less characters if the string-building doesn't take place in a function, like I did before :

## Delphi, 181

```
program a;{$APPTYPE CONSOLE}function s(c,i:byte):string;begin if(i>0)then Exit(Char(c)+s(c,i-1));if(c<122)then Exit(s(c+1,c-95));end;begin if(s(97,1)=ParamStr(1))then Write(42);end.

```

Note that the output doesn't need a newline, so WriteLn() became Write().
> 3 votes

# Answer
## PHP - 45 characters

I'm surprise nobody posted any answer that used hashing. It's a very size effecient way of testing for exact string.

```
echo md5($argv[1],1)!='¯è a@ÛÚƒ:ïT�p'?:42;

```

The data is kind of hard to copy/paste since there is a null-byte in the middle of the code. Here's an hex-dump of the code for testing purposes.

> 65 63 68 6f 20 6d 64 35 28 24 61 72 67 76 5b 31 5d 2c 31 29 21 3d 27 af e8 a0 61 40 db da 7f 11 0f 83 3a ef 54 00 70 27 3f 3a 34 32 3b
> 3 votes

# Answer
**Scala 79**

```
 if((for(i <- 1 to 26;j<-1 to i)yield(96+i).toChar).mkString==args(0))print(42)

```
> 3 votes

# Answer
# Pyth, 14

```
*42qzsm*dhxGdG

```

Just constructs the necessary string, then compares with the input and multiplies by 42.
> 3 votes

# Answer
# Brachylog (2), 15 bytes, language postdates challenge

```
⊇Ạ∧?o?ọtᵐ~⟦₁+₁₆

```

Try it online!

And now for an answer which works on a completely different principle to most seen here. This is a function submission (the question doesn't specify what sort of submission is desired, but functions are permitted by default).

## Explanation

This answer works by defining a sort of string: those which a) contain all lowercase letters of the alphabet, b) are in sorted order, and c) for which taking the number of occurrences of each character in the string produces a sequence of consecutive integers starting from 1. (It should be clear that there are many such strings, but the one we want to special-case is the shortest.) Then if the string fulfils those criteria, we add 16 to the number of distinct characters in the string; this will produce 42 if the string is the one the question asks us to special-case, and at least 43 in all other cases. (If the string fails any of the criteria to belong to the category, the function will end in failure, which is kind-of like throwing an exception.)

Here's how to interpret the source code:

```
⊇Ạ∧?o?ọtᵐ~⟦₁+₁₆
⊇Ạ               {the input} contains all lowercase letters
  ∧              and
   ?o?           the input sorts to itself
                 {and; implied when two conditions overlap}
     ?ọ          the {character, number of occurrences} pairs for the input
       tᵐ        when the second element of each is taken
         ~       create an output that could have been produced by
          ⟦₁     outputting the list of integers from 1 to some input inclusive;
            +₁₆  add 16 to that input {and output it}

```
> 3 votes

# Answer
# R, ~~60~~ 58

```
~~`if(readline()==paste0(rep(letters,1:26),collapse=""))cat(42)`~~
```

```
if(scan(,"")==paste(rep(letters,1:26),collapse=""))cat(42)
```

Thanks for the suggestion by @giusppe
> 3 votes

# Answer
## Python (84)

Assumes a trailing newline at the end of the input.

```
import sys
if''.join(c*chr(c+96)for c in range(27))+'\n'==sys.stdin.read():print 42

```
> 2 votes

# Answer
## JavaScript (91 93 94 98 102 116)

Usage: `a('string')`, returns `42` if valid according to spec, or `0`.

```
function a(z){for(i=r='';i++<26;)for(j=i;j--;)r+=String.fromCharCode(i+96);return(z==r)*42}

```

http://jsfiddle.net/g25M3/6/

**Edit**: Removed `var` and eliminated two spaces in `for (`.

**Edit 2**: Changed `j>0` to `j`, and

1. `return (z==r)?42:0;` to
2. `return z==r?42:0`

**Edit 3**: Initialize `i` with `i=''`, change

1. `(z==r)?42:0` to
2. `(z==r)*42`

**Edit 4**: Change

1. `for(;i<27;i++)` to
2. `while(i++<26)`

**Edit 5**: Change

1. `i=r='';while(i++<26)` to
2. `for(i=r='';i++<26;)` and
3. `for(j=i;j;j--)` to
4. `for(j=i;j--;)`
> 2 votes

# Answer
**PHP  92 88 87 chars**

```
function _($a){for($i=97;$i<123;$i++)for($j=$i-96;$j;$j--)$b.=chr($i);echo($b==$a)*42;}

```

**EDIT**

Replaced `$j<0` with `$j` and `return $b==$a?42:0;` with `echo $b==$a?42:0;`

Replaced `echo $b==$a?42:0;` with `echo($b==$a)*42;`
> 2 votes

# Answer
## Python - 62 chars

```
print("".join(x*chr(x+96) for x in range(27))==raw_input())*42

```
> 2 votes

# Answer
## Perl, 49 46 characters

to be used in a program, not on the command line

`$..=chr($*+96)x$* for 1..26;$.eq(pop)&&print '42'`

```
join('',map$_ x++$x,'a'..'z')eq pop&&print'42'

```

Regards

rbo

Edit: Idea ripped from Ventero
> 2 votes

# Answer
**ECLiPSe Prolog - 173**

```
c(_,[],_):-!. c(A,M,N):-length(L,N),checklist('='(A),L),append(F,L,M),P is N-1,B is A-1,c(B,F,P). ?- read_string(end_of_file,351,S),string_list(S,L),c(122,L,26),writeln(42).

```
> 2 votes

# Answer
## JavaScript 1.8, 99 chars

```
function c(x)(x.replace(/([a-z])\1*/g,function(m)!(a-m.length)*m.charCodeAt(0)-96-a++,a=1)==0)*a+15

```

I dare you to make sense of it :)
> 2 votes

# Answer
# PHP - 59

Assumes at least 1 input is provided over cli

```
echo md5($argv[1])!='afe8a06140dbda7f110f833aef540070'?:42;

```

It more or less works, except that md5 is can technically have duplications with the hashing algo.
> 2 votes

# Answer
# VBA 91

There weren't any VBA answers but this works:

```
Function f(t)
    For i = 1 To 26
        o = o & String(i, Chr(i + 96))
    Next
    f = -42 * (t = o)
End Function

```
> 2 votes

# Answer
## PowerShell v2+, 47 bytes

```
42*(-join(1..26|%{,[char]($_+96)*$_})-ceq$args)

```

Constructs a range `1..26`, feeds that through a loop with `|%{...}`. Each iteration we use the comma operator to construct an array literal of the current `[char]` multiplied by the current loop number. We then `-join` that all together to construct the string `abbcccdddd...` and then use a case-sensitive `-ceq` comparison against our input `$args`, which will result in either `$TRUE` or `$FALSE`. In PowerShell, Boolean values can be implicitly cast as `1` or `0`, respectively, which is what happens here with the `42*`. Will print out `42` iff the input is `abbccc...zzzzzzzzzzzzzzzzzzzzzzzzzz` and will output `0` otherwise.
> 2 votes

# Answer
### K, 26 Bytes

```
{(::;42)x~,/(1+!26)#'.Q.a}
{(::;42)x~,/(1+!26)#'.Q.a}"hello"
{(::;42)x~,/(1+!26)#'.Q.a}"abbcccddddeeeeeffffffggggggghhhhhhhhiiiiiiiiijjjjjjjjjjkkkkkkkkkkkllllllllllllmmmmmmmmmmmmmnnnnnnnnnnnnnnoooooooooooooooppppppppppppppppqqqqqqqqqqqqqqqqqrrrrrrrrrrrrrrrrrrsssssssssssssssssssttttttttttttttttttttuuuuuuuuuuuuuuuuuuuuuvvvvvvvvvvvvvvvvvvvvvvwwwwwwwwwwwwwwwwwwwwwwwxxxxxxxxxxxxxxxxxxxxxxxxyyyyyyyyyyyyyyyyyyyyyyyyyzzzzzzzzzzzzzzzzzzzzzzzzzz"
42

```

Thanks
> 2 votes

# Answer
# APL (Dyalog), ~~18~~ 17 bytes

```
42/⍨⍞≡819⌶⎕A/⍨⍳26

```

Try it online!

Four obvious bytes can be saved if we are allowed to use uppercase.

`42` 42

`/⍨` if (lit. replicated by)

character input

is identical to

`819⌶` the lowercased

`⎕A`**A**lphabet

`/⍨` replicated by

one through

`26` 26
> 2 votes

# Answer
# 05AB1E, 7 bytes

```
AƶJQ42*

```

Try it online!

---

Wellp, 05AB1E keeps evolving.
> 2 votes

# Answer
## Javascript, 145 bytes

Only uses recursion

```
((function(i,k,l){return(String.fromCharCode(97+i)==l[k+i])&&((i<25)?arguments.callee(++i,k+i,l):l.length==k+i+1)}).call(this,0,0,line)==true)*42

```

This approach checks each character along the way instead of creating the valid string to compare against. So, is the 'g' actually in the correct position, then return true. Finally check that the length is what is expected. Any falses on the way cause a '0' to be returned.

Thanks for the hint regarding the \*42 at the end
> 1 votes

# Answer
# Lua 98

```
i=io.read()e=0 for k=1,26 do s,e=i:find(string.char(96+k):rep(k),e+1)_=e or os.exit()end print(42)

```
> 1 votes

# Answer
# **Clojure** \- 61 chars

```
(fn[a](if(=(mapcat #(repeat%(char(+% 96)))(range 1 27))a)42))

```

Exploits the following facts:

* Clojure can interpret any string automatically as a sequence of chars
* I can use the range of numbers from 1 to 26 to both create the characters and repeat them the correct number or times to generate the "correct" input
> 1 votes

# Answer
## Delphi, 127

```
var b:Char;c,i:Int8;begin repeat if i<0then i:=c;Read(b);if c+97<>Ord(b)then Exit;i:=i-1;c:=c+Ord(i<0)until i=27;Write(42);end.

```

This one reads the string from the input, compares it as it goes, writes 42 when the input matches up until the last `z`.

## Delphi, 157

```
var b:pchar;c,i:byte;begin b:=CmdLine+85;c:=97;i:=1;repeat Inc(b);if b^<>Char(c)then Exit;Dec(i);if i>0then Continue;c:=c+1;i:=c-96;until i=27;Write(42);end.

```

## Delphi, 188

```
program a;{$APPTYPE CONSOLE}var b:pchar;c,i:byte;begin b:=CmdLine+85;c:=97;i:=1;repeat Inc(b);if(b^<>Char(c))then Exit;Dec(i);if(i>0)then Continue;c:=c+1;i:=c-96;until(i=27);Write(42);end.

```

This version doesn't use a function, which saves quite a few characters when compared to the previous version of this technique :

## Delphi, 213

```
program a;{$APPTYPE CONSOLE}function t(b:pchar;c,i:byte):byte;begin repeat Inc(b);if(b^<>Char(c))then Exit(0);Dec(i);if(i>0)then Continue;c:=c+1;i:=c-96;until(i=27);t:=42;end;begin WriteLn(t(CmdLine+77,97,1));end.

```

Alas a bit long, mostly because Delphi's long keywords, and the need to initialize console applications before they can write output.

Also note that I incremented CmdLine by 77 characters, as that was the offset I needed to skip over my local executablepath (Delphi has no direct argument pointer). Adjust to match your own setup (could lead to 1 less character when offset \< 10).
> 1 votes

# Answer
# C++ (110 chars)

Assumes use of the std namespace, headers, etc. And make use of everything *not* specified in the question (whether it can output something else when the string doesn't match, etc.)

```
int main(int, char **c)
{
    string s(c[1]), t;
    for(int i=1; i < 27; i++) {
        for(int j=0; j < i; j++) {
            t += i+96;
        }
    }
    cout << 42 + s.compare(t);
}

```
> 1 votes

# Answer
## Javascript 144

Probably can be significantly improved, recursion has always been a head far for me.

**Compressed**

```
function r(a,b,d,c){c++;if(b<d)a+=r(a,b+1,d,c);for(i=0;i<c;i++)a=String.fromCharCode(b)+a;return a}function q(a){if(q==r(a,97,122,0))return 42};

```

**Less Compressed**

```
function r(s, c, x, w){
    w++;
    if(c < x)
        s += r(s, c + 1, x, w);
    for(i = 0; i < w; i++)
        s = String.fromCharCode(c) + s;
    return s;
}
function q(z){
    if(q==r(z,97, 122, 0))
        return 42;
}

alert(q("rgrg"));

```
> 1 votes

# Answer
## Groovy - 64

```
print args[0]!=(1..26).collect{"${(char)it+96}"*it}.join()?'':42

```
> 1 votes

# Answer
# Q, 31 30

```
{$[x~(,/)(1+(!)26)#'.Q.a;42;]}

```
> 1 votes

# Answer
# Burlesque, 24

```
@azr@{J**96.-.*}ms==42.*

```

Pretty standard solution.

```
@az r@            creates range from 'a to 'z
{                 start mapping the code block to each element
    J ** 96 .-    duplicates the current and gets it position in the alphabet (n)
    .*            duplicates the element n times
}ms               end mapping, with the added flourish to concatenate the mapped block
==42.*            got this from isaacg above me.

```

Try it here. Note that Burlesque takes anything that's before the code as input, so mess up the "abb...zzz" string to see it fail.
> 1 votes

# Answer
# C++, 157 154

**Compressed (headers included) \[154 characters\]:**

```
#include<iostream>
#include<string>
int i,j;int main(){std::string h;std::cin>>h;for(;i<26;i++)while(j<=i+i*(i+1)/2)(h[j]=='a'+i)?j++:j;std::cout<<42;}

```

**Compressed (headers and using namespace std assumed like in this answer) \[100 characters\]:**

```
int i,j;int main(){string h;cin>>h;for(;i<26;i++)while(j<=i+i*(i+1)/2)(h[j]=='a'+i)?j++:j;cout<<42;}

```

**Not compressed (with headers):**

```
#include <iostream>
#include <string>
using namespace std;

int i, j;
int main()
{
    string h;
    cin >> h;
    for(i = 0 ; i < 26 ; i++)
        while(j <= i+i*(i+1)/2)
            (h[j] == 'a'+i)?j++:j;
    cout << 42;
}

```

**Explanation:**

* **int i,j; int main():** i and j are initialized to 0 with 8 characters instead of 12 (int i=0,j=0;)
* **j\<=i+i\*(i+1)/2:** use of the triangular number formula
* **(h\[j\]=='a'+i)?j++:j:** endless loop trick when j is not incremented

> Edit. Headers and using statements counted
> 1 votes

# Answer
# , 21 bytes

Program:

```
   42*(u:96+(]#])i.27)-:

```

Usage:

```
   42*(u:96+(]#])i.27)-: 'abbcccddddeeeeeffffffggggggghhhhhhhhiiiiiiiiijjjjjjjjjjkkkkkkkkkkkllllllllllllmmmmmmmmmmmmmnnnnnnnnnnnnnnoooooooooooooooppppppppppppppppqqqqqqqqqqqqqqqqqrrrrrrrrrrrrrrrrrrsssssssssssssssssssttttttttttttttttttttuuuuuuuuuuuuuuuuuuuuuvvvvvvvvvvvvvvvvvvvvvvwwwwwwwwwwwwwwwwwwwwwwwxxxxxxxxxxxxxxxxxxxxxxxxyyyyyyyyyyyyyyyyyyyyyyyyyzzzzzzzzzzzzzzzzzzzzzzzzzz'
42

```

Explanation:

```
   42*                    NB. Multiply 42 to
      (
       u:                 NB. Convert all to characters
         96+              NB. Add 96 to all
            (]#])         NB. "]" copies the i.27, and 1 4 # 1 2 gives 1 2 2 2 2 for example
                 i.27     NB. 0 1 2 3 ... 26 (not 27)
                     )
                      -:  NB. matches the right hand side (return 1 if matches, 0 otherwise)

```
> 1 votes

# Answer
# Reng v.3.2, 88 bytes

(Noncompeting, postdates question.)

```
2#y2#z"a"1Ø         Ø3r1\
:1+>y1-?!v$z1+:#y#zRzeq!^
   ^  :y#<
i sve(*?v)
?~n>$ 2.>076**

```

This is one heckuvan answer.

## Initial

```
2#y2#z"a"1Ø

```

Stores 2 to `y` (the temporary counter) and `z` (the overall counter), and initiates the stack with `"a"` then goes to the next line.

## Loop

```
:1+>y1-?!v$z1+:#y#zRzeq!^
   ^  :y#<

```

First, `:1+` duplicates the previously made run of characters and increments it to work with the next one. Then...

### Generating N copies of a number

```
   >y1-?!v
   ^  :y#<

```

This loops until `y == 0`. Once `y` is zero, we exit the loop. Otherwise, we put `y - 1` back into `y` and duplicate the character being worked with it.

### Breaking out of this loop

```
          $z1+:#y#zRzeq!^

```

This drops `y` from the conditional and increments and duplicates `z`, which is then put into y and z. Then, if `R` (26 + 1) is `z`, we go to the next part. Otherwise, the loop continues again.

## Transition

```
                    Ø3r1\
                        ^

```

This goes out of the loop, pushes `1` (our equality counter), reverses the stack, and goes to the third line.

## Final

```
i sve(*?v)
?~n>$ 2.>076**

```

`i sve(*?v)` loops until (a) there is no input or (b) the equality counter is 0. In the first case, the first `v` is met, and we drop the -1 bit, skip over the `>0` bit (`2.`), and output 42 (`6*7*equality`), skipping `~` with a conditional. Otherwise, the second `v` is encountered, and a zero is pushed before the `76**`, so this makes it zero. The conditional activates the `~` (exit program) command because the TOS is falsey, and thus no output is given.
> 1 votes

# Answer
# 05AB1E, ~~14~~ 13 bytes

```
AvyN>×}JIQi42

```

Try it online!

**Edit**: Saved 1 byte thanks to @Okx.

My first official PPCG submission!

Explanation:

```
AvyN>×}JIQi42

A              # push alphabet to stack
 v    }        # foreach in ToS, element = y, index = N
  y            # push letter to stack
    N>         # increment index by 1
     ×         # repeat the letter (index + 1) times, push to stack

       J       # join stack together
        I      # push input to stack
         Q     # check if string == input
          i42  # if so, push 42 to stack, implicitly print

```
> 1 votes

# Answer
# Jelly, 13 bytes in Jelly's codepage, language postdates challenge

```
26RØa,ZŒṙ⁼×42

```

Try it online!

## Explanation

```
26RØa,ZŒṙ⁼×42
     ,         Start with a pair of:
   Øa            the lowercase alphabet (['a', 'b', …, 'y', 'z'])
26R              and the list [1, 2, 3, 4, …, 25, 26]
      Z        Swap rows and columns (yielding [['a', 1], ['b', 2], …, ['z', 26]])
       Œṙ      Run-length decode (yielding the string in the original question)
         ⁼     1 if equal to {the original input}, 0 otherwise
          ×42  Multiply by 42

```

So we end up outputting 42 if the string is the special-cased string, or 0 otherwise.
> 1 votes

# Answer
### Pyth, 10 bytes

```
*42qSs.__G

```

Explanation:

```
*42qSs.__G
        _G     Reversed alphabet "zyx...a"
      ._       Prefixes ["z", "zy", ..., "zyx...a"]
    Ss         Concatenated and sorted "abbccc...zzz"
   q      Q    Compare with implicit input
*42            42 if the input matches, 0 otherwise

```
> 1 votes

# Answer
# Excel VBA, 50 Bytes

Anonymous VBE immediate window function that takes input from cell `[A1]` and outputs `42` iff the input is equal to the expected output, else `0`

```
For i=1To 26:s=s+String(i,i+96):Next:?([A1]=s)*-42

```
> 1 votes

# Answer
## Python, 56 bytes

```
lambda s:s=="".join(c*chr(c+96)for c in range(27))and 42

```

I know I'm late to the party, but both of the existing Python answers were full programs, which seemed suboptimal. Returns `42` for the specified input, `False` for everything else.
> 1 votes

# Answer
# 05AB1E, 9 bytes

```
ASā×JQi42

```

Try it online!

### Explanation

```
ASā×JQi42   Argument: s
AS          Push alphabet as array
  ā×J       Each character as many times as its index
     Q      Compare with s
      i42   If true, output 42

```
> 1 votes

# Answer
# Perl 6, 32 bytes

```
{42 if $_ eq[~] 'a'..'z'Zx 1..*}

```
> 1 votes

# Answer
# C (gcc), 86 bytes

```
i,c;main(a){for(i=0;i++<a&&(c=getchar())==a+96;);a>26&&c<0?puts("42"):i>a&&main(a+1);}

```

Try it online!
> 1 votes

# Answer
# Husk, ~~12~~ 10 bytes

```
&42=ṘN…"az

```

-2 bytes thanks @Zgarb!

Try it online!

```
       "az  -- constant string: "az"
      …     -- fill the range 'a'..'z': "abc...xyz"
    ṘN      -- replicate each character [1..] times: "abbccc...zzz..z"
   =        -- is input equal to that string?
&42         -- if it is then 42 else 0

```
> 1 votes

# Answer
# Sinclair ZX81/Timex TS1000/1500 BASIC, ~138 tokenized BASIC bytes

```
 1 LET A$="A"
 2 LET C=NOT PI
 3 FOR I=SGN PI TO VAL "25"
 4 LET A$=A$+CHR$ (CODE "A"+I)
 5 LET C=C+SGN PI
 6 IF C<=I THEN GOTO VAL "4"
 7 LET C=NOT PI
 8 NEXT I
 9 INPUT B$
10 IF A$=B$ THEN PRINT "42"

```

This is the most byte efficient solution I could think of for the technology in question (whilst retaining readability, of course), however, building the string `A$` does take a while so be patient (or set an emulator to a decent speed above 3.5Mhz).
> 1 votes

# Answer
# Japt, 11 bytes

```
;¶CËpEÄ
*42

```

Try it
> 1 votes

# Answer
# Zsh, ~~97~~ ~~56~~ ~~52~~ 51 bytes

Builds the string then compares `$1`. If the input doesn't match the magic string, some integer other than 42 (or an error message) is printed. Try it online!!

```
for c ({a..z})repeat $[++i];s+=$c
<<<$[${#s#$1}+42]

```

My original solution: ~~97bytes~~ (ascii evaluate input)
@GammaFunction's solutions: ~~56bytes~~ ~~52 bytes~~ 51 bytes (main solution)
Example: `for c ({a..z})s+=${${(l:++i:)}//?/$c};[ $s = $1 ]&&<<<42`
> 1 votes

# Answer
# Bash, 68 bytes

```
for c in {a..z};{ for ((i=++j;i--;)){ s+=$c;};}
[ $s = $1 ]&&echo 42

```

Build the string, compare and print. If the input string has spaces in it, the `[ comparison ]` will break, but return falsy anyway.

Try it online!
> 1 votes

# Answer
# Vyxal, 11 bytes

```
kaf₄ɾ*∑=42*

```

Try it Online!

```
kaf         # lowercase alphabet, flattened into char list
   ₄ɾ*      # Repeat by 1..26
      ∑=    # Concatenate all, 1 if input is equal to string, 0 if not
        42* # Multiply by 42

```
> 1 votes

# Answer
## Groovy, 70

```
a=[];(1..26).each{a+=[(char)it+96]*it};if(args[0]==a.join(''))print 42

```
> 0 votes

# Answer
## C++

```
$ cat main.cpp | wc -m -l
16     269

```

**Not compressed**

Recursive ok routine checks string for abbcccdddd....

```
#include <iostream>

bool ok(char *c)
{
    char *s = c;
    while(*c && *c == *s) c++;
    return (c - s == *s - 'a' + 1) && ((*c == 0 && *s == 'z') || ok(c));
}

int main(int c, char **v)
{
    if(c > 1 && ok(v[1]))
        std::cout << 42 << std::endl;

    return 0;
}

```

**Second version**

```
$ cat main.cpp | wc -m -l
15     239

```

Without recursion

```
#include <stdio.h>

bool ok(char *c)
{
    char i,j;
    for(i = 'a'; i <= 'z'; ++i)
    for(j = 'a'; j <= i; ++j)
        if(*c++ != i) return 0;
    return !*c;
}

int main(int c, char **v)
{
    return c > 1 && ok(v[1]) && printf("42"), 0;
}

```
> 0 votes

# Answer
# JavaScript (1.8), 103 characters

```
function f(s,i)i===+i?s.length-i-1||s.charCodeAt()-i-97:s&&s.match(/(.)\1*/g).some(f)+s.length!=351|42

```

Here's my rather long attempt in JavaScript... returns 42 if the string is the valid string, 43 otherwise.

Here's a prettier, earlier version with whitespace:

```
function f(s) {
  return s && s.match(/(.)\1*/g).some(function(x,i) {
    return x.length-i-1 || x.charCodeAt()-i-97
  })+s.length==351 && 42
}

```

and another version, closer to the final version (modulo whitespace removal)

```
function f(s,i) {
  return i===+i
       ? s.length-i-1 || s.charCodeAt()-i-97
       : s&&s.match(/(.)\1*/g).some(f)+s.length!=351 | 42
 }

```
> 0 votes

# Answer
## R, 99

```
f=function(x){s="";for(i in 1:26)s=c(s,(rep(letters[i],each=i)));s=paste(s,collapse="");if(x==s)42}

```

Usage:

```
f("test")
f("abbcccddddeeeeeffffffggggggghhhhhhhhiiiiiiiiijjjjjjjjjjkkkkkkkkkkkllllllllllllmmmmmmmmmmmmmnnnnnnnnnnnnnnoooooooooooooooppppppppppppppppqqqqqqqqqqqqqqqqqrrrrrrrrrrrrrrrrrrsssssssssssssssssssttttttttttttttttttttuuuuuuuuuuuuuuuuuuuuuvvvvvvvvvvvvvvvvvvvvvvwwwwwwwwwwwwwwwwwwwwwwwxxxxxxxxxxxxxxxxxxxxxxxxyyyyyyyyyyyyyyyyyyyyyyyyyzzzzzzzzzzzzzzzzzzzzzzzzzz")
[1] 42

```
> 0 votes

# Answer
# Javascript, 104

```
function f(x){var a="";for(b=97;b<123;b++)a+=Array(b-95).join(String.fromCharCode(b));if(x==a)return 42}

```

Should be pretty obvious, but it creates the string and then tests it against the input.

If I can golf this down any further, please let me know.
> 0 votes

# Answer
# Oracle SQL 11.2, 148 bytes

```
SELECT 42 FROM(SELECT MAX(TRANSLATE(SYS_CONNECT_BY_PATH(LPAD(' ',LEVEL+1,CHR(64+LEVEL)),';'),'A; ','A'))s FROM DUAL CONNECT BY LEVEL<27)v WHERE:1=s;

```
> 0 votes

# Answer
# Haskell, ~~45~~ 51 bytes

```
f x|x==zip[1..]['a'..'z']>>=uncurry replicate->"42"

```

`zip [1..] ['a'..'z']` produces the list `[(1,'a'), (2,'b'), ...]`.

`uncurry replicate` has the type `(Int, a) -> [a]`, and `uncurry replicate (n, v)` produces a list of `n` copies of `v`.

`>>=` applies `uncurry replicate` to the `zip`ped list, and concatenates the results.

Finally, that string compared to the argument and returns "42" if it is equal, or crashes.

(edited b/c I'm dumb and didn't notice the return requirement)
> 0 votes

# Answer
# Pylongolf2, 21 bytes

```
con1968701440=?42~¿

```

Explanations:

```
con1968701440=?42~¿
c                   read input
 on                 hash it and then convert into integer
   1968701440       push the (aaa.zz) thing (but hashed) into the stack
             =      compare them
              ?     if true,
               42~  output 42
                  ¿ end if statement.

```

That last inverted question mark messed me up by 2 bytes :|
> 0 votes

# Answer
# SmileBASIC, 58 bytes

```
DEF F S
FOR I=1TO 26C$=C$+CHR$(I+64)*I
NEXT?42OR C$!=S
END

```

I had to make it a function since the maximum `INPUT` length is 128 characters.
> 0 votes

# Answer
# R, 74 bytes

```
g=function(x){if(x==paste(rep(rep(letters[1:26]),(1:26)),collapse=""))42}

```
> 0 votes

# Answer
# Java 8, ~~103~~ ~~101~~ 87 bytes

```
s->{String r="";for(char c=96,i;++c<123;)for(i=96;i++<c;)r+=c;return r.equals(s)?42:0;}

```

Returns `0` for everything that doesn't match the expected input.

**Explanation:**

Try it here.

```
s->{                       // Method with String parameter and integer return-type
  String r="";             //  String starting empty
  for(char c=96,i;++c<123;)//  Loop (1) over the lowercase alphabet:
    for(i=96;i++<c;)       //   Inner loop (2) `c-i` amount of times:
      r+=c;                //    Append that many of the current letter to the String
                           //   End of inner loop (2) (implicit / single-line body)
                           //  End of loop (1) (implicit / single-line body)
  return r.equals(s)?      //  If the input equals the String:
    42                     //   Return 42
   :                       //  Else:
    0;                     //   Return 0
}                          // End of method

```
> 0 votes

# Answer
# Axiom, 141 bytes

```
f(x:String):NNI==(c:=96;i:=0;k:=1;repeat(c:=c+1;i:=i+1;for j in 1..i repeat(k>#x or ord(x.k)~=c=>return 0;k:=k+1);c=122=>break);k=#x+1=>42;0)

```

ungolf

```
--It would return 42 if the string in input it is as string above this codegolf question
--it would return 0 in other cases; suppose Axiom ord() return 97..122 for a..z (ascii)
ff(x:String):NNI==
   c:=96;i:=0;k:=1
   repeat
      c:=c+1; i:=i+1           -- c='a'=97 i=1 k=1
      for j in 1..i repeat
               k>#x or ord(x.k)~=c=>return 0
               k:=k+1
      c=122=>break -- c==122 is 'z'
   k=#x+1=>42
   0

```
> 0 votes

# Answer
# Japt, ~~13~~ ~~12~~ 11 bytes

Outputs `42` or `false`.

```
;¶CËpEÄÃ©#*

```

Try it online
> 0 votes

# Answer
# Python 3, 58 bytes

```
lambda s:[42][''.join([i*chr(i+96)for i in range(27)])!=s]

```

Try it online!

Six years late to the party?

*golfed 4 bytes off when I realized I could've used `!=` instead of `1-` `==`*
> 0 votes

# Answer
# JavaScript, 86 Bytes

```
c="";for(x=0;x<26;)c+=String.fromCharCode(x+97).repeat(++x);alert(prompt("")==c?42:0);

```

White spaced:

```
c="";
for(x=0;x<26;)
    c+=String.fromCharCode(x+97).repeat(++x);
alert(prompt("")==c?42:0);

```

I couldn't indent by 4 spaces for some reason. Not sure if using alert is allowed.

Edit: Fixed indent
> 0 votes

# Answer
# Jelly, 9 bytes

```
ØaxJ¤⁼×42

```

Try it online!

There is already a 13 byte Jelly answer, but the user had their account deleted, and it felt wrong to just edit in this code.

## How it works

```
ØaxJ¤⁼×42 - Main link. Argument: s (string)   e.g. "abc"
Øa  ¤     - Yield the lowercase alphabet           "abc...xyz"
   J      - Yield range(length)                    [1 2 ... 25 26]
  x       - Repeat (vectorising).                  "abbccc..."
     ⁼    - Equal to the input? Call the A         0
      ×42 - Multiply 42 by A                       0

```
> 0 votes

# Answer
# Pyth - 21 Bytes

```
V26=Y+Y*@GNhN;IqsYz42

```

Explanation:

```
V26=Y+Y*@GNhN;IqsYz42  z is initialised to input and Y to empty list
V26                    For N from 0 to 25
   =Y                  Set Y to
      Y                Y
     +                 Plus
        @GN            Item N of the alphabet
      *                Times
           hN          N plus one
             ;         End For
              I        If
                sY     Concatenate all elements of Y
               q       Equals
                  z    z
                   42  Print 42

```
> 0 votes

# Answer
# Javascript (ES6) 84 bytes

```
s=>[...Array(26)].map((_,i)=>String.fromCharCode(97+i).repeat(i+1)).join("")==s?42:0

```

I don't think an explanation is needed, but here's one anyway:

```
s=> // input
    [...Array(26)] // preparing alphabet array
    .map((_,i)=>String.fromCharCode(97+i).repeat(i+1)) // using the current index to get the corresponding letter and repeat it as many times as it's 1-index
    .join("")==s?42:0 // Join the array into a string and check if equal to input.

```
> 0 votes

# Answer
# APL NARS 14 chars

```
{⍵≡⎕a/⍨⍳26:42}

```

it return 42 for the request string, nothing if something else.

```
  f←{⍵≡⎕a/⍨⍳26:42}
  w←(⍳26)/⎕a
  f 2
  f w
42
  f 'str'

```
> 0 votes

# Answer
# AWK, 65 bytes

```
{for(;i<26;)for(j=++i;j--;)L=L sprintf("%c",i+96);$0=L==$0?42:0}1

```

Try it online!

Maybe I should develop a golfing version of `AWK`, but until then, here is my `AWK` solution :)
> 0 votes

# Answer
# K (oK), 14 bytes

**Solution:**

```
42*(&!27)~-96+

```

Try it online!

**Explanation:**

Returns `42` if the input matches the "abbccc..." otherwise `0`.

```
42*(&!27)~-96+ / the solution
          -96+ / subtract 96 from the input (vectored)
         ~     / matches?
   (&!27)      / where (&) til (!) 27. Generates 1 2 2 3 3 3 4 4 4 4... sequence
42*            / multiply result (0 false or 1 true) by 42

```
> 0 votes

# Answer
# Python 2, 69 bytes

```
x=""
for i in range(26):x+=chr(97+i)*(i+1)
if raw_input()==x:print 42

```

Try it online!
> 0 votes

# Answer
# Julia 0.6, 55 bytes

```
s->join("$c"^i for (i,c) in enumerate('a':'z'))==s?42:0

```

Try it online!
> 0 votes

# Answer
# Lua, 80 bytes

```
c=""for i=1,26 do c=c..string.char(i+96):rep(i)end print(c~=io.read()and""or 42)

```

Try it online!

Brief explanation: creates the string and then compares it with the input. Output is an empty string or 42.
> 0 votes

# Answer
# Wren, 72 bytes

Generate the range 'a'..'z'. Multiply the string-converted value by the value - 96. Join the list. Check whether the input is equal to this string.

```
Fn.new{|A|A==(1..26).map{|x|String.fromCodePoint(x+96)*(x)}.join()?42:0}

```

Try it online!
> 0 votes

# Answer
# Thunno 2, 9 bytes

```
Ạdż×J=42×

```

Attempt This Online!

#### Explanation

```
Ạdż×J=42×  # Implicit input
Ạd         # Lowercase alphabet, split into a list of characters
  ż×       # Each multiplied by their 0-based index
    J=     # Equals the input string?
      42×  # Multiply by 42
           # Implicit output

```
> 0 votes

---
Tags: code-golf, string
---