title: Calculate the prime factors

text:
# Question
Title: Calculate the prime factors
We had a prime factorization challenge a while ago, but that challenge is nearly six years old and barely meets our current requirements, so I believe it's time for a new one.

## Challenge

Write a program or function that takes as input an integer greater than 1 and outputs or returns a list of its prime factors.

## Rules

* Input and output may be given by any standard method and in any standard format.
* Duplicate factors must be included in the output.
* The output may be in any order.
* The input will not be less than 2 or more than 231 \- 1.
* Built-ins are allowed, but including a non-builtin solution is encouraged.

## Test cases

```
2 -> 2
3 -> 3
4 -> 2, 2
6 -> 2, 3
8 -> 2, 2, 2
12 -> 2, 2, 3
255 -> 3, 5, 17
256 -> 2, 2, 2, 2, 2, 2, 2, 2
1001 -> 7, 11, 13
223092870 -> 2, 3, 5, 7, 11, 13, 17, 19, 23
2147483646 -> 2, 3, 3, 7, 11, 31, 151, 331
2147483647 -> 2147483647

```

## Scoring

This is , so **the shortest code in bytes wins.**

# Answer
> 15 votes
# Python 2, 55 bytes

```
f=lambda n,k=2:n/k*[0]and(f(n,k+1),[k]+f(n/k,k))[n%k<1]

```

Try it online!

# Answer
> 15 votes
# Pyth, 1 byte

```
P

```

I like Pyth's chances in this challenge.

# Answer
> 11 votes
## Python 2, 53 bytes

```
f=lambda n,i=2:n/i*[f]and[f(n,i+1),[i]+f(n/i)][n%i<1]

```

Tries each potential divisor `i` in turn. If `i` is a divisor, prepends it and restarts with `n/i`. Else, tries the next-highest divisor. Because divisors are checked in increasing order, only the prime ones are found.

As a program, for 55 bytes:

```
n=input();i=2
while~-n:
 if n%i:i+=1
 else:n/=i;print i

```

# Answer
> 8 votes
# Mathematica, ~~38~~ 30 bytes

Thanks @MartinEnder for 8 bytes!

```
Join@@Table@@@FactorInteger@#&

```

# Answer
> 6 votes
# Haskell, 48 bytes

```
(2%)
n%1=[]
n%m|mod m n<1=n:n%div m n|k<-n+1=k%m

```

Try it online! Example usage: `(2%) 1001` yields `[7,11,13]`.

# Answer
> 5 votes
# Jelly, 2 bytes

```
Æf

```

Try it online!

# Answer
> 4 votes
# JavaScript (ES6), 44 bytes

```
f=(n,x=2)=>n-1?n%x?f(n,x+1):[x,...f(n/x)]:[]

```

Horribly inefficient due to the fact that it iterates from 2 up to every prime factor, including the last. You can cut the time complexity dramatically at the cost of 5 bytes:

```
f=(n,x=2)=>x*x>n?[n]:n%x?f(n,x+1):[x,...f(n/x,x)]

```

# Answer
> 4 votes
# Cubix, ~~37~~ 32 bytes

```
vs(...<..1I>(!@)s)%?w;O,s(No;^;<

```

Try it online! or Watch it in action.

# Answer
> 4 votes
# Haskell, 47 bytes

Basically this checks all integers `2, 3, 4, 5, ...` for divisors of `n`. If we find one, we factor that out and repeat the process until we get to `1`.

```
f 1=[]
f n=(:)<*>f.div n$until((<1).mod n)(+1)2

```

Try it online!

# Answer
> 3 votes
# Actually, 6 bytes

```
w`in`M

```

Try it online!

Explanation:

```
w`in`M
w       factor into primes and exponents
 `in`M  repeat each prime # of times equal to exponent

```

# Answer
> 3 votes
# J, 2 bytes

```
q:

```

~~Body must be at least 30 characters.~~

# Answer
> 3 votes
# MATL, 2 bytes

```
Yf

```

Try it online!

Obligatory "boring built-in answer".

# Answer
> 3 votes
# Japt, 2 bytes

```
Uk

```

A built-in `k` used on the input `U`. Also refers to a country.

Test it online!

# Answer
> 3 votes
# Vyxal, 1 byte

```
ǐ

```

Try it Online!

Just the built-in. But that's boring, so

## Vyxal, ~~16~~ 8 bytes

```
K~æ~Ǒ$ẋf

```

Try it Online!

## Explained

```
ʀ~æ~Ǒ$ẋf
ʀ~æ      # From the all numbers in the range [0, input], keep only those that are prime
   ~Ǒ    # Without popping anything, get the multiplicity of each prime divisor - this leaves the stack as [divisors, multiplicities]
     $ẋ  # Swap the two items and repeat each divisor multiplicity times
       f # Flatten and output that

```

# Answer
> 2 votes
# tone-deaf, 3 bytes

This language is quite young and not really ready for anything major yet, but it can do prime factorization:

```
A/D

```

This will wait for user input, and then output the list of prime factors.

# Answer
> 2 votes
# MATLAB, 6 bytes

I think this does not require any explanation.

```
factor

```

# Answer
> 2 votes
## Batch, 96 bytes

```
@set/an=%1,f=2,r=0
:l
@set/af+=!!r,r=n%%f
@if %r%==0 echo %f%&set/an/=f
@if %n% gtr 1 goto l

```

# Answer
> 2 votes
# , ~~53~~ 52 bytes

```
p=function(n,i=2)if(n>1)c(i[m<-!n%%i],p(n/i^m,i+!m))

```

Try it online!

Recursive function: overflows the stack limit and errors on TIO for the last test case.

---

# , ~~59~~ 58 bytes

```
function(n,i=2)while(n>1)if(n%%i)i=i+1 else{show(i);n=n/i}

```

Try it online!

Non-recursive function: does not error for large primes, but will still take a very long time to run (and so times-out without erroring on TIO for the last test case anyway).

# Answer
> 2 votes
# CellTail, 166 bytes

```
N,(u,u,_),N:1,(u,1),(0,2);(0,2),N,N:1,N,N;N,(u,v,0),N:1,(v,1),(u/v,2,(u/v)%2);N,(u,v,w),N:1,(u,v+1,u%(v+1)),N;a&(_,_,_),N,N:1,a,N;_,(v,1),_:1,v,N;N,u,N:1,(u,2,u%2),N;

```

Try the demo

## Explanation:

Base case, when we reach the end switch to a recursion resistant tuple and pass a message right to break it. Then the message right sends a 1 to prevent recursion when the tuple has broken.

```
N,(u,u,_),N:1,(u,1),(0,2);(0,2),N,N:1,N,N;

```

We have found a factor, try again in the cell to the right with `(u/v)`

```
N,(u,v,0),N:1,(v,1),(u/v,2,(u/v)%2);

```

We have not found a factor, try another.

```
N,(u,v,w),N:1,(u,v+1,u%(v+1)),N;

```

Copy 3-tuples from left to current

```
a&(_,_,_),N,N:1,a,N;

```

Break recursion resistant tuples. Hopefully the next step the value from the right will throw a 1 to break the recursion.

```
_,(v,1),_:1,v,N;

```

Base case, start with trying 2 as a factor.

```
N,u,N:1,(u,2,u%2),N;

```

# Answer
> 1 votes
# Bash \+ coreutils, 19 bytes

```
factor|sed s/.*:.//

```

Try it online!

# Answer
> 1 votes
## Pyke, 1 byte

```
P

```

Try it here!

Prime factors builtin.

# Answer
> 1 votes
# Hexagony, 58 bytes

Not done golfing yet, but @MartinEnder should be able to destroy this anyway

Prints out factors space-separated, with a trailing space

Golfed:

```
2}\..}$?i6;>(<...=.\'/})."@...>%<..'':\}$"!>~\{=\)=\}&<.\\

```

Laid-out:

```
     2 } \ . .
    } $ ? i 6 ;
   > ( < . . . =
  . \ ' / } ) . "
 @ . . . > % < . .
  ' ' : \ } $ " !
   > ~ \ { = \ )
    = \ } & < .
     \ \ . . .

```

Explanation coming later.

# Answer
> 1 votes
# 05AB1E, 1 byte

```
Ò

```

Try it online!

# Answer
> 1 votes
# CJam, 2 bytes

```
mf

```

cjam.aditsu.net/...

This is a function. Martin, it seems I was sleepy.

# Answer
> 1 votes
## C, 92 bytes

```
int p(int n){for(int i=2;i<n;i++)if(n%i==0)return printf("%d, ",i)+p(n/i);printf("%d\n",n);}

```

Ungolfed version:

```
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>

int prime(int number) {
    for (int i = 2; i < number; i++) {
        if (number % i == 0) {
            printf("%d, ", i);
            return prime(number / i); //you can golf away a few bytes by returning the sum of your recursive function and the return of printf, which is an int
        }                             //this allow you to golf a few more bytes thanks to inline calls
    }
    printf("%d\n", number);
}

int main(int argc, char **argv) {
    prime(atoi(argv[1]));
}

```

# Answer
> 1 votes
# Japt, 1 byte

```
k

```

Try it online!

# Answer
> 1 votes
# Java (OpenJDK), 259 bytes

```
import java.util.*;interface g{static void main(String[]z){int a=new Scanner(System.in).nextInt();int b=0;int[]l={};for(int i=2;i<=a;i++){for(;a%i<1;l[b-1]=i){l=Arrays.copyOf(l,b=l.length+1);a/=i;}}for(int i=0;i<b;i++)System.out.print(l[i]+(i<b-1?", ":""));}}

```

Try it online!

# Answer
> 1 votes
# PHP, 51 bytes

```
for($i=2;1<$a=&$argn;)$a%$i?$i++:$a/=$i*print"$i ";

```

Try it online!

# Answer
> 1 votes
# Ruby, ~~48~~ 45 bytes

```
->x{r,*c=2;0while x%r>0?x>=r+=1:c<<r&&x/=r;c}

```

Try it online!

# Answer
> 1 votes
# C (gcc), 51 bytes

```
i;f(n){for(i=2;i<=n;)n%i?i++:printf("%d ",i,n/=i);}

```

Try it online!

# Answer
> 1 votes
# Pyt, 1 byte

Boring built-in answer

Try it online!

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

```
IT1WP2K%ZB|:N,:M?t;

```

Try it online!

## Explanation

```
IT                  < [n]     read input to n then mark cell (T)
  1WP     |         < [n m=2] from 2 onwards (m=1;while m:m++;)
     2K%ZB          < [n m+1] copy two elements, mod, break if n%m==0
           :N       < [n m] (< where n%m==0) print m with newline
             ,:M?t; < [n/m] (< new n)        divide, if not 1 redo from T else exit

```

# Answer
> 1 votes
# APL(NARS), 1 char, 2 bytes

```
π

```

That is...

# Answer
> 1 votes
# Haskell, 47 bytes

```
f 1=[]
f n=[k:f a|k<-[2..],a<-[1..n],a*k==n]!!0

```

Try it online!

```
f 1=[]
f n=[k:f(div n k)|k<-[2..],mod n k<1]!!0

```

Try it online!

# Answer
> 1 votes
# Regex (ECMAScript or better), 28 bytes

```
(?=(xx+?)\1*$)(x+)\2*(?=\2$)

```

Takes its input in unary, as a string of `x` characters whose length represents the number. Returns its output as the list of matches' `\1` captures, whose lengths represent the prime factors.

Try it online! \- ECMAScript
Try it online! \- Perl
Try it online! \- PCRE1
Try it online! \- PCRE2
Try it online! \- Java
Try it online! \- Boost
Try it online! \- Python
Try it online! \- Python (`import regex`)
Try it online! \- Ruby
Try it online! \- .NET

```
(?=(xx+?)\1*$)  # Assert tail ≥ 2; \1 = the smallest prime factor of tail
(x+)\2*(?=\2$)  # tail = \2 = the largest proper divisor of tail

```

# Regex (.NET), 31 bytes

```
((?=(xx+?)\2*$)(x+)\3*(?=\3$))*

```

Returns its output as the list of captures on the Balancing Group 2 stack, whose lengths represent the prime factors.

Try it online!

```
(
    (?=(xx+?)\2*$)  # Push the smallest prime factor of tail onto the Group 2
                    # capture stack.
    (x+)\3*(?=\3$)  # tail = \3 = the largest proper divisor of tail
)*                  # Loop the above as many times as possible, minimum zero.

```

This regex naturally handles an input of 1 correctly, returning an empty list.

# Regex (Perl / PCRE / Boost / Ruby), 41 bytes

```
(?=(xx+?)\1*$)(?=(x+)\2+$).*?\K\1(?=\2?$)

```

Returns its output as the list of matches, whose lengths represent the prime factors.

Try it online! \- Perl
Try it online! \- PCRE
Try it online! \- Boost
Try it online! \- Ruby

This requires Perl/PCRE/Boost/Ruby due to the use of the `\K` (set start of match) function. Other than that, no features more advanced than those available in ECMAScript/Python are used.

```
(?=(xx+?)\1*$)   # \1 = smallest prime factor of tail
(?=(x+  )\2+$)   # \2 = largest proper divisor of tail
.*?\K\1(?=\2?$)  # Manipulate the match to be \1 exactly, using "\K" to start
                 # the match before it;
                 # if tail was prime, tail = 0, else tail = \2

```

# Answer
> 1 votes
**Rockstar, 659 characters**

Not really my code, but quite fun, source quoted at bottom:

```
Depression takes your hope and your light
While your hope is as high as your light
Put your hope without your light into your hope

If your hope is gone
Give back yes

Give back lies

Listen to your heart
My world is selflessness
Your faith is forgiveness
While your heart is bigger than your faith and depression taking your heart, my world
Whisper my world
Put your heart over my world into your heart

Build my world up
While your heart is bigger than your faith
While your heart is bigger than your faith and depression taking your heart, my world
Scream my world
Put your heart over my world into your heart

Build my world up, up

```

Source: https://github.com/RockstarLang/rockstar/blob/main/examples/factorization.rock

Rockstar language: https://codewithrockstar.com/

# Answer
> 1 votes
# Thunno 2, 1 byte

```
f

```

Try it online!

Built-in for "prime factors".

## Thunno 2, 11 bytes

```
(ḅ}ÐRḣœḊhß÷

```

Try it online!

No factor built-ins.

#### Explanation

```
(ḅ}ÐRḣœḊhß÷  # Implicit input
(            # While loop:
 ḅ}          #   (condition)  not equal to 1
   Ð         #   (body)  triplicate the current number
    Rḣ       #           pop one copy and push [2..n]
      œḊh    #           first number it's divisible by
         ß   #           print this without popping
          ÷  #           and divide the number by this

```

# Answer
> 1 votes
# ForWhile, 30 bytes

`{1;[1+;[;;%!:[.';/;;1=!]):)..}`

Takes integer on stack as input, pushes prime factors on the stack

online interpreter

## Explanation

{    }   \ anonymous procedure taking value n on stack as input
 1       \ push 1
  ;[     \ repeat n times
    1+   \ increase the counter by 1
      ;[ \ repeat up to n times

 ;;%!             \ check if n is divisible by the counter
     :[.        ] \ if yes
        ';/;;1=!  \ divide n by the counter and check if n is not equal to 1

   )     \ break the loop if the top stack value is zero
    :)   \ continue at the start of the loop
      .. \ cleanup stack
```
</code></pre>

# Answer
> 0 votes
# Perl 6,  ~~77~~  64 bytes

```
{my$a=$_;.is-prime??$_!!map ->\f{|({$a%f||($a/=f)&&f}...^*!= f)},(2... *>$a)}

```

Try it

```
{my$a=$_;map ->\f{|({$a%f||($a div=f)&&f}...^ f>*)},(2... *>$a)}

```

Try it ( Note: it doesn't have enough time allotted to finish )

---

A much more performant version is slightly longer at 100 bytes.

```
{my$a=$_;map ->\f{|({$a.is-prime??($/=$a)&&($a=0)||$/!!($a%f||($a div=f)&&f)}...^ f>*)},(2... *>$a)}

```

Try it

---

## Expanded: <sup><sub>(64 byte version)</sub></sup>

```
{
  my $a = $_;  # the input ｢$_｣ is read-only by default
  map
    -> \f {
      |(              # slip ( flattens into outer list )

        # generate sequence of 0 or more ｢f｣s
        {
          $a % f      # is it not evenly divisible

          ||          # if it is evenly divisible
          ($a div=f)  # divide it
          &&          # and
          f           # return ｢f｣
        }
        ...^   # keep doing that until
        f > *  # ｢f｣ is bigger
      )

    },

    # do that over the following list

    (2 ... * > $a) # generate a sequence from 2
                   # up to whatever the value of $a
                   # is at the time of the check
}

```

# Answer
> 0 votes
## VB.NET, 86 bytes

Had this sitting around from some Project Euler programs. Removed the optimizations in the interest of shortness, and this is the result. Naturally, VB is very verbose, so it's fairly long. I'm not counting the leading whitespace. It can be omitted, but is easier to read with it.

This takes an integer as a parameter, and prints the prime factors with a comma after. There is a trailing comma at the end.

```
Sub A(a)
    For i=2To a ' VB re-evaluates a each time, so the /= at the end of the loop shortens this
        While a Mod i=0 ' this is a factor. We've grabbed primes before this, so this must be a prime factor
            Console.Write(i &",") ' output
            a/=i ' "mark" the prime as "used"
        End While
    Next
End Sub

```

# Answer
> 0 votes
# Perl 6, 51 bytes

A recursive solution:

```
sub f(\n,\d=2){n-1??n%d??f n,d+1!!(d,|f n/d,d)!!()}

```

# Answer
> 0 votes
# Ruby, 61 bytes

```
require'prime';->x{x.prime_division.flat_map{|x|[x[0]]*x[1]}}

```

Shortest builtin-version I could think of.

# Answer
> 0 votes
# Python 2, 55 bytes

```
n=input();i=1
while~-n:
 i+=1
 while n%i<1:print i;n/=i

```

Try it online!

# Answer
> 0 votes
# Scala 3, 83 bytes

```
def f(n:Int,k:Int=2):Seq[Int]=if(n<k)Seq();else if(n%k==0)k+:f(n/k,k);else f(n,k+1)

```

Attempt This Online!

# Answer
> 0 votes
# Nibbles, 10.5 bytes (21 nibbles)

```
!;`.$/$=2|,$~%@$>>@/

```

Attempt This Online!

```
  `.                        # iterate while unique
    $                       # starting with input:
     /$                     #   itself divided by
       =2|,$~%@$            #   its first divisor;
 ;                          # now, remember this list
!                           # and zip it with
                  >>@       # itself without its first element
                     /      # by division

```

---
Tags: code-golf, primes, factoring
---


title: Name your novel disease

text:
# Question
Title: Name your novel disease
# Introduction

The current coronavirus disease is officially named **COVID-19**, from the 3 words **co**rona **vi**rus **d**isease, and the year 20**19**. (Technically it's coronavirus, making 2 words, but whatever...)

Given this example, we can apply this naming convention to name other potential diseases.

# Challenge

You will be given 3 words and a year.

* Take the first letters of the first 2 words, up to and including the first vowel, and append them together.
* Then, append the first letter of the 3rd word.
* Finally, append the character `-`, followed by the last 2 digits of the year.

Thus, `corona,virus,disease,2019 -> co + vi + d + - + 19 -> covid-19`.

### Challenge rules

* It is guaranteed that each of the three words have at least one vowel. For the purposes of this challenge, vowels are defined as the letters `a, e, i, o, u`.
* You may assume that words consist only of lowercase letters `a-z`, or only uppercase letters `A-Z` if you prefer. Your output may be in either case.
* It's guaranteed that the date is exactly four digits.
* Input may be specified in any format, as long as there is a delimiter between the words. For example, `['corona', 'virus', 'disease', '2019']`, `corona,virus,disease,2019`, `[['corona', 'virus'], 'disease', 2019]` and `corona virus disease 2019` are all valid inputs.

This is , so shortest answer wins.

# Example test cases

```
corona,virus,disease,2019 -> covid-19
computer,addiction,syndrome,1970 -> coas-70
code,golf,fun,2020 -> cogof-20
a,ba,ca,1234 -> abac-34
tree,string,create,9000 -> trestric-00
love,time,cholera,1985 -> lotic-85

```

# Answer
# Python 3, ~~83~~ 81 bytes

```
lambda a,b,c,d:g(*a)+g(*b)+c[0]+"-"+d[2:]
g=lambda c,*s:c[:c in"aeiou"]or c+g(*s)

```

Try it online!

*-2 bytes thanks to @JonathanAllan!*

### Explanation:

`g` is a recursive function that takes in a splatted string and return the string, truncated after the first vowel.

* `lambda c,*s` gather the splatted string into the first character `c` and the rest `s`.
* `c[:c in"aeiou"] or c+g(*s)` evaluates to:
    + if `c` is a vowel, then `c[:c in"aeiou"]` evaluates to `c[:1]` which is `c`. Since `c` is Truthy, it is returned.
    + if `c` is not a vowel, then `c[:c in"aeiou"]` evaluates to `c[:0]` aka the empty string. The empty string is Falsy, so `c+g(*s)` (the recursive case) is returned.

**Old solution, kept here for sentimental reason**

### Python 3, 89 bytes

```
lambda a,b,c,d:g(a)+g(b)+c[0]+"-"+d[2:]
g=lambda s:s[:[x in"aeiou"for x in s].index(1)+1]

```

Try it online!
> 20 votes

# Answer
# Java 8, ~~82~~ ~~74~~ ~~71~~ ~~67~~ 61 bytes

```
s->s.replaceAll((s="(.*?[aeiou]).*,")+s+"(.).*,..","$1$2$3-")

```

-8 bytes thanks to *@ValueInk*.
-6 bytes thanks to *@Nevay*.

Input as a single comma-separated string like in the challenge description.

Try it online.

**Explanation:**

```
s->                // Method with String as both parameter and return-type
  s.replaceAll(    //  Regex-replace the match with the replacement (see below)
                   //   As match:
    (s="(.*?[aeiou]).*,")+s
                  //     Repeat this String twice (re-using the input-variable)
    +"(.).*,..",  //     and append this String
    "$1$2$3-")    //    And as replacement: use this String

```

*Regex explanation:*

```
(.*?[aeiou]).*,(.*?[aeiou]).*,(.).*,..  # MATCH:
 .*                                     #  0 or more characters
   ?                                    #  which are optional to lower their priority
    [aeiou]                             #  followed by a vowel
(          )                            #  Stored in capture group 1
            .*                          #  Followed by some optional characters
              ,                         #  and a comma
               (.*?[aeiou]).*,          #  Same again, with capture group 2
                               .        #  Then a single character
                              ( )       #  Stored in capture group 3
                                 .*     #  Followed by some optional characters
                                   ,    #  and a comma again
                                    ..  #  Followed by 2 characters

$1$2$3-                                 # REPLACEMENT:
$1$2$3                                  #  The contents of groups 1, 2, and 3
      -                                 #  Appended with a literal "-"

```

Note how the two trailing digits of the input-String aren't touched, and will still be there after the replacement.
> 9 votes

# Answer
# Retina 0.8.2, 26 bytes

```
\B.*¶\d.
-
([aeiou]).*¶
$1

```

Try it online! Link includes test suite. Takes lowercase words and year on separate lines, but test suite splits each test case on commas automatically for the convenience of the user. Explanation:

```
\B.*¶\d.
-

```

Truncate the last word after the first character, remove the first two digits of the year, and join the two together with a `-`.

```
([aeiou]).*¶
$1

```

Truncate each of the first two words after the first vowel, and join everything together.
> 8 votes

# Answer
# Japt v2.0a0 `-P`, 15 bytes

```
®¯ÒZb\vÃpVÎ'-W¤

```

Saved a byte thanks to @Shaggy (`s2` -\> `¤`)

Try it

```
®¯ÒZb\vÃpVÎ'-W¤           Input: ["corona" "virus"] "disease" "2019"
®      Ã                  Map ["corona" "virus"] to
   Zb\v                     Index of first vowel in word
  Ò                         Add one
 ¯                          Slice 0..index+1
                          ["co" "vi"]
        p                 Append the following:
         VÎ               A) First letter of third word
           '-             B) "-"
             W¤           C) Last two digits of year
                          ["co" "vi" "d" "-" "19"]
-P                        Implicit join -> "covid-19"

```
> 6 votes

# Answer
# Jelly,  ~~18~~  17 bytes

```
ḣe€ØcM$ḢƊ€⁴Ḣ”-3⁵ṫ

```

A full program accepting arguments `['word1', 'word2'] 'word3' 'year'` which prints the result.

**Try it online!**

### How?

```
ḣe€ØcM$ḢƊ€⁴Ḣ”-3⁵ṫ - Main Link: [word1, word2]
         €        - for each (w in [word1, word2]):
        Ɗ         -   last three links as a monad:
      $           -     last two links as a monad:
  €               -       for each (character, c of w):
 e                -         (c) exists in?:
   Øc             -           vowels = "AEIOUaeiou"
     M            -       maximal indices (i.e (sorted) indices of vowels in w)
ḣ                 -     head to index (vectorises across the list of indices):
       Ḣ          -     head (the first such head-to-index result)
          ⁴       - program's 2nd argument, word3
                  - ...N.B. a nilad here forces Jelly to smash the previous list
                  -         together and print to STDOUT.
           Ḣ      - head - i.e. the first character of the third word
            ”-    - literal '-' character
                  - ...N.B. again a nilad here forces a print of the previous
                  -         result, the first character of the third word.
              3   - literal three
               ⁵  - program's 3rd argument, year
                ṫ - tail from index (i.e. "2019" -> "19")
                  - implicit print (of these two characters)

```
> 6 votes

# Answer
# Bash \+ Core utilities, ~~58~~ 55 bytes

```
sed -E 's/([aeiou]).*/\1/;3s/\B.*/-/;4s/..//'|tr -d \\n

```

Try it online!

*3 bytes shorter through the use of \B, thanks to user41805.*

Accepts newline-delimited input on stdin.

Output on stdout.
> 4 votes

# Answer
# Python 3, 86 bytes

```
lambda t,c,y:''.join(re.sub('([aeiou]).*',r'\1',s)for s in t)+c[0]+'-'+y[2:]
import re

```

Try it online!

Inputs the first two words in a tuple followed by the third word and then year as a string.
> 3 votes

# Answer
# QuadS, 33 bytesSBCS

Takes lowercase multi-line input.

```
∊('-',⍨⊃)¨@3⊢⍵
^.*?[aeiou]|\d.$
&

```

Try it online!

`&` Search for and return

`^.*?[aeiou]|\d.$` initial letters ending with a vowel, or a trailing digit with another character

`⊢⍵` on that

`(``)¨@3`**at** the third match:

pick the first character

`'-',⍨` prepend a dash

**ϵ**nlist (flatten)
> 3 votes

# Answer
# Perl 5 `-p`, 48 bytes

```
$p='(.*?[aeiou]).*? 'x2;s/$p(.).*(..)/$1$2$3-$4/

```

Try it online!

Basically, a straight forward regex to pick out the relevant parts and put them back together.
> 3 votes

# Answer
# Zsh, 41 bytes

```
<<<${(Mj::)@[1,2]#*[aeiou]}${3[1]}-${4:2}

```

Try it online!

Normally `${param#pattern}` is prefix removal, adding the `(M)` flag keeps the prefix instead.

```
<<<${(Mj::)@[1,2]#*[aeiou]}${3[1]}-${4:2}
   ${      @[1,2]         }                 # first two args
   ${(M   )      #*[aeiou]}                 # match shortest prefix ending with a vowel
   ${( j::)               }                 # join the resulting words on empty string
                           ${3[1]}          # third param, first char
                                   ${4:2}   # fourth param, starting at third char

```

If the first two words can be given as a single space seperated argument (as in `corona virus` `disease` `2019`), then one byte can be saved for **40 bytes**:

```
<<<${(Mj::)${=1}#*[aeiou]}${2[1]}-${3:2}

```

Try it online!
> 2 votes

# Answer
# JavaScript (ES6),  ~~65~~  63 bytes

Takes input as 4 distinct strings.

```
(a,b,[c],[,,d,e])=>a.match(r=/.*?[aeiou]/)+b.match(r)+c+'-'+d+e

```

Try it online!

---

# JavaScript (ES6), 71 bytes

Takes input as `["word1", "word2", "word3", "year"]`.

```
a=>'012-3'.replace(/\d/g,i=>a[i].match([,,/./,/..$/][i]||/.*?[aeiou]/))

```

Try it online!
> 2 votes

# Answer
# Python 3, 86 bytes

```
lambda a,c,d:''.join(re.sub("([aeiou]).*",r"\1",x)for x in a)+c[0]+"-"+d[2:]
import re

```

Accepts input like `["corona", "virus"], "disease", "2019"`

Try it online!
> 2 votes

# Answer
# Icon, 95 bytes

```
procedure f(a,b,c,d)
return a[1:1+upto(t:='aoeiu',a)]||b[1:1+upto(t,b)]||c[1]||"-"||d[3:0]
end

```

Try it online!
> 2 votes

# Answer
# perl -anE, 65 bytes

```
s/[aeiou]\K\w+// for@F[0,1];$F[2]=~s/.\K.*//;$F[3]=~s/../-/;say@F

```
> 2 votes

# Answer
# Ruby, 48 bytes

```
->a,b,c,d{a[r=/.*?[aeiou]/]+b[r]+c[0]+?-+d[2,2]}

```

Try it online!
> 2 votes

# Answer
# APL (Dyalog Unicode), ~~44~~ 40 bytes

Original (and more fun): `{t←{⍵↑⍨⊃⍸⍵∊'aeiou'} ⋄ ,/⍎¨'tt12',¨' ↑↓',¨⍵}`

Improved: `{d←2∘↓⋄t←{⍵↑⍨⊃⍸⍵∊'aeiou'}⋄,/⍎¨'tt⊃d',¨⍵}`

Try it online!1

Takes input of form: `'''word''' '''word''' '''word''' '''dd-dd'''`

This one is just a lot of fun and rather unconventional. Not necessarily the shortest, but that's the price of fun! Have a feeling `t` function can be further golfed but haven't managed to. The rest I'll leave as is because it's primarily neat; concision is secondary for once. Plus, who could possibly stomach messing with *42* bytes!

I'll add the full explanation tomorrow, however in short it's all just an abuse of the fact that we were trusted to determine the input format. Thus, one can pass it to the function as data and prepend (with a couple zips) the necessary manipulations, before evaluating the pieces of the list. This requires taking strings of strings as input; In *Dyalog APL*, quotes are escaped by doubling them, so printing `'''Hello world'''` yields `'Hello world'`.

Before each element is evaluated and concatenated: `{'tt12',¨' ↑↓',¨⍵}` yields `t 'corona' , t 'virus' , 1↑'disease' , 2↓'20-19'`. The two strings in the function are zipped together with the input to yield a piece of code containing the manipulations we desire for each piece. To clarify, `t` is the function which takes a string and returns the first elements until a vowel is spotted. The function `t` is defined in the right half of the code.

1Due to the dangerous 'execute' () operator, I've only gotten it to run online in TIO under dzaima's dialect, which is the TIO page linked above. However, as long it's downloaded, it'll work in any old flavor of Dyalog, so I'm insisting on marking it as such in the title!
> 2 votes

# Answer
# Erlang (escript), 124 bytes

```
f(A,B,C,D)->g(A)++g(B)++[hd(C)]++"-"++string:slice(D,2).
g([H|T])->case"aeiou"==("aeiou"--[H])of true->[H]++[g(T)];_->H end.

```

Try it online!

## Explanation

f(A,B,C,D)->g(A)++g(B)                                            % Slice things up to vowels for A and B
                      ++[hd(C)]                          % Add the head of C
                                        ++"-"++string:slice(D,2). % Add a - and tail of D

g([H|T])-> % Recursive function for the vowel slicing
case"aeiou"==("aeiou"--[H])of true-> % If head isn't vowel:
[H]++[g(T)];                         % Return head + slicing (tail)
_->H end.                            % Else: return head
```
</code></pre>
> 2 votes

# Answer
# Perl 6, 44 bytes

```
{S:g/<[aeiou]><(.*?\s//}o{S/\S<(\S*\s\d./-/}

```

Try it online!

Combination of two substitution regexes, the first to replace the third word and year with the letter dash date, and the second to remove anything between a vowel and a space (removing the space as well).
> 2 votes

# Answer
# Charcoal, 26 bytes

```
⭆Ｅ²Ｓ…ι⌊ΦＥaeiou⊕⌕ιλλ§Ｓ⁰-✂Ｓ²

```

Try it online! Link is to verbose version of code. Takes lowercase words either space or newline-separated. Explanation:

```
⭆Ｅ²Ｓ

```

For the first two words...

```
…ι⌊ΦＥaeiou⊕⌕ιλλ

```

... find the positions of the vowels, and take the minimum of those that exist, and truncate the word after that point.

```
§Ｓ⁰

```

Print the first letter of the third word.

```
-

```

Print a `-`.

```
✂Ｓ²

```

Input the year as a string and print the last two digits.
> 1 votes

# Answer
# Red, ~~94~~ 92 bytes

```
func[a b c d][g: func[t][head clear find/tail t
charset"aoeiu"]rejoin[g a g b c/1"-"at d 3]]

```

Try it online!
> 1 votes

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

```
(a,[b],c)=>a.map(x=>/.*?[aeiou]/.exec(x)).join``+b+'-'+c[2]+c[3]

```

Try it online!
> 1 votes

# Answer
# 05AB1E, 55 bytes

```
1(UI#v´yXiн?}Tи`žMvykˆ}¯ʒ2+≠}WD.ïiŠŠs>£?}X>U}"-"?UR2£R?

```

Try it online!

I'm sure this can be optimized in so many different ways, but I'll throw it in here anyway.
> 1 votes

# Answer
# , 106 bytes

```
function(a,b,c,y,s=substr,f=function(x)s(x,1,regexpr("[aeiou]",x)))paste0(f(a),f(b),s(c,1,1),"-",s(y,3,4))

```

Try it online!

Say hello to R's atrocious handling of strings. I wouldn't be surprised if this could be golfed significantly.
> 1 votes

# Answer
# 05AB1E, 22 bytes

```
εžMySkd0šÅ¡н}Iн'-I¦¦)S

```

Inputs as `["corona","virus"]`, `disease`, and `2019`.
Output as a list of characters.

Try it online or verify all test cases. (Feel free to remove the `J`oin in the footer to see the actual output-list.)

**Explanation:**

```
ε                      # Map over the first (implicit) input-list of strings:
 žM                    #  Push the vowel constant "aeiou"
   y                   #  Push the current word we're mapping over
    S                  #  Convert it to a list of characters
                       #   i.e. "virus" → ["v","i","r","u","s"]
     k                 #  Get the index of each character in the string (-1 if not found)
                       #   → [-1,2,-1,4,-1]
      d                #  Check for each index if it's non-negative (>= 0)
                       #   → [0,1,0,1,0]
       0š              #  Prepend a 0 to this list
                       #   → [0,0,1,0,1,0]
         Å¡            #  Split the string we're mapping over on the truthy indices
                       #   → ["vi","ru","s"]
           н           #  And only leave the first part
                       #   → "vi"
            }I         # After the map: push the second input-string
              н        # Pop and push just its first letter
                       #  i.e. "disease" → "d"
               '-     '# Push a literal "-"
                 I     # Push the third input-integer
                  ¦¦   # Remove its first two digits
                       #  i.e. 2019 → 19
                    )  # Wrap all values on the stack into a list
                       #  → [[["c","o"],["v","i"]],"d","-","19"]
                     S # And convert it to a flattened list of characters
                       #  → ["c","o","v","i","d","-","1","9"]
                       # (after which it is output implicitly as result)

```
> 1 votes

# Answer
# ssed -R, 70 bytes

Expects input through stdin in lowercase separated by spaces, e.g., `corona virus disease 2019`.

```
s_(.+?(?![aeiou])).*? (.+?(?![aeiou])).*? (.).*? \d\d(\d\d)_\1\2\3-\4_

```

`ssed`, known as "super sed", has PCRE which gives us non-greedy matchers.

```
(.+?(?![aeiou])).*?<space>
                ^^^^^^^^^^: Eats the rest of the word before the space
    ^^^^^^^^^^^: Before a character that is a vowel
 ^^^: Match fewest number of characters

```

The rest is simple enough once you understand the above. If anyone is interested I can go into more depth but I think this is enough.

The try-it-online thing doesn't have `ssed` installed in Bash. To try it locally you can install `ssed` through Homebrew by `brew install ssed` if you're on a mac. If anyone knows a way to get a working try-it-online I'll add it.
> 1 votes

# Answer
# C (gcc), 96 bytes

```
#define z write(1,*a++,strcspn(*a,"aeiou")+1)
f(a,y)char**a;{z;z;printf("%c-%.2d\n",**a,y%100);}

```

*-13 bytes and all concerns resolved thanks to ceilingcat!*

Try it online!
> 1 votes

# Answer
# dirt, 38

```
([^,]*[aeiou]{[^,]*,})*.{[^,]*,..}'-..

```

Accepts a comma-separated list of strings and outputs the disease name.

e.g. `dirt disease.dirt -i "corona,virus,disease,2019"` prints `covid-19`.

## Explanation

```
(
 [^,]*      # match and output any number of non-comma characters
 [aeiou]    # match and output a vowel
 {          # with no output:
  [^,]*     # - match any number of non-comma characters
  ,         # - match a comma
 }
)*          # run the above any number of times.
.           # match and output 1 character.
{           # with no output:
 [^,]*      # - match any number of non-comma characters
 ,          # - match a comma
 ..         # - match 2 characters
}
'-          # output a hyphen
..          # match and output 2 characters

```
> 1 votes

# Answer
# Vyxal , 15 bytes

```
ƛA1ḟ›Ẏ;∑?h\-?2ȯ

```

Try it Online!

#### Explanation

```
ƛA1ḟ›Ẏ;∑?h\-?2ȯ  # Implicit input
ƛ     ;          # Apply to both of the first two words:
 A1ḟ             #  Index of the first vowel
    ›            #  Incremented to make 1-indexed
     Ẏ           #  That many characters from the start
       ∑         # Join into a string
        ?h       # First character of the last word
          \-     # Push a "-"
            ?2ȯ  # Last two characters of the year
                 # Implicit output of joined stack

```
> 1 votes

# Answer
# Python 3, ~~128~~ ~~124~~ ~~122~~ 119 bytes

```
a,b,c,d=input().split()
def g(a):
 for i in a:
  if i in'aeiou':return a[:a.find(i)+1]
print(g(a)+g(b)+c[0]+'-'+d[2:])

```

Try it online!

Pretty new, probably overcomplicated.

edit 1: saved four bytes by moving a part from print() to function

edit 2: saved two more bytes thanks to @surculose-sputum

edit 3: another three bytes thanks to @surculose-sputum
> 0 votes

# Answer
# Perl 5, + `-pF` 41 bytes

```
($_)=$.<3?/^.*?[aeiou]/g:$.<4?@F:s/../-/r

```

Try it online!
> 0 votes

# Answer
# FEU, 57 bytes

```
s/([^aeiou]+.).+,([^aeiou]+.).+,(.).+,\d+(\d\d)/\1\2\3-\4

```

Try it online!
> 0 votes

# Answer
# Octave, 112 bytes

```
v='aeiou',a=@arrayfun
p=@(x)x(1:find(a(@(y)any(a(@(z)z==y,v)),x),1))
@(i)[p(i{1}) p(i{2}) i{3}(1) '-' i{4}(3:4)]

```

Try it online!
> 0 votes

# Answer
# Thunno 2 `j`, 14 bytes

```
2ɲ'-$h$ıDṃ1Ȯ⁺ɱ

```

Try it online!

#### Explanation

```
2ɲ'-$h$ıDṃ1Ȯ⁺ɱ  '# Implicit input
2ɲ               # Last two characters of the year
  '-            '# Push a "-"
    $h           # First character of the last word
      $ı         # Apply to both of the first two words:
         ṃ1Ȯ     #  Index of the first vowel
            ⁺    #  Incremented to make 1-indexed
        D    ɱ   #  That many characters from the start
                 # Implicit output of joined stack

```
> 0 votes

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


title: Leyland Numbers

text:
# Question
Title: Leyland Numbers
Given a natural number \\$n\\$, return the \\$n\\$-th Leyland number.

### Leyland Number

Leyland numbers are positive integers \\$k\\$ of the form

$$k = x^y + y^x$$

Where \\$x\\$ and \\$y\\$ are integers strictly greater than 1.

They are enumerated in ascending order.

**EDIT:** @DigitalTrauma suggested I include following "definition":

> Imagine we throw \\$x^y+y^x\\$ in a bag for all possible values of \\$x\\$ and \\$y\\$, and avoid throwing in duplicates. Then we sort that bag. The sorted bag is our sequence.

### Details

You may use 0 or 1 based indexing, whatever suits you best.

Your program must be able to output at least all Leyland numbers less than the maximum of signed 32-bit integers. (The last Leyland number below this limit is `1996813914`, at index `82`.)

### Test cases

The first few terms are following:

```
8, 17, 32, 54, 57, 100, 145, 177, 320, 368, 512, 593, 945, 1124

```

A076980 in OEIS, except for the first entry. Note that because of that additional first entry, the indices on OEIS are shifted by one.

More can be found in the OEIS b-file

# Answer
# MATL, ~~16~~ ~~15~~ 13 bytes

```
Q:Qt!^t!+uSG)

```

Output is 1-based.

**Try it online!**

### Explanation

```
Q    % Take input n. Add 1
:Q   % Range [2 ... n+1]. This is enough to be used as x and y
t!   % Duplicate and transpose
^    % Power, element-wise with broadcast. Gives 2D, square array with x^y
     % for all pairs of x and y
t!   % Duplicate and transpose. Gives square array with y^x
+    % Add, element-wise
u    % Keep unique elements. This linearizes (flattens) the 2D array
S    % Sort
G)   % Get the n-th entry. Implicitly display

```
> 11 votes

# Answer
# Java 10, ~~225~~ ~~221~~ ~~219~~ ~~216~~ ~~206~~ ~~204~~ ~~193~~ ~~192~~ ~~130~~ 129 bytes

```
n->{var S=new java.util.TreeSet();for(int i=56,t;i<840;)S.add(Math.pow(i/28,t=i%28+2)+Math.pow(t,i++/28));return S.toArray()[n];}

```

0-indexed

-2 bytes (221 → 219) saved by replacing `1996813915` with `(1L<<31)` thanks to *@LeakyNun*.
-3 bytes (219 → 216) thanks to *@LeakyNun* and *@Frozn* with something I forgot myself..
-10 bytes (216 → 206) by changing Java 7 to 8.
-2 bytes (206 → 204) by replacing `ArrayList` with `Vector` thanks to *@TAsk*.
-11 bytes (204 → 193) by removing `s<(1L<<31)&`, since the question states "***at least** all Leyland numbers less than the maximum of signed 32-bit integers*".
-1 byte (193 → 192) by changing `Vector` to `Stack`.
-62 bytes (192 → 130) by switching to Java 10 and using `var`; removing the `Collection.sort`, `import java.util.*;`, if-statement and temp-long `s` by using a `java.util.TreeSet` (which is a set of unique values and sorts automatically); and using `Double` and `Object` return-type instead of `Long` so we can remove the `(int)(...)` cast and `<Long>`.
-1 byte (130 → 129) thanks to *@ceilingcat* by changing the two nested `[2,30]` loops to a single `[56,840]` loop.

Try it here

**Explanation:**

```
n->{                             // Method with integer parameter and Object return-type
  var S=new java.util.TreeSet(); //  Create a sorted Set, initially empty
  for(int i=56,t;i<840)          //  Loop `i` in the range [56,840]
    t.add(                       //   Add to the Set:
      Math.pow(i/28,             //    `i` integer-divided by 28
               t=i%28+2)         //    to the power `i` modulo-28 + 2
      +Math.pow(t,               //    And add `i` modulo-28 + 2
                i++/28));        //    to the power `i` integer-divided by 28
                                 //    (and increase `i` by 1 afterwards with `i++`)
  return S.toArray()             //  Convert the sorted Set to an Object-array
           [n];}                 //  And return the value at the input-integer index

```
> 6 votes

# Answer
## Haskell, 52 bytes

```
r=[2..31]
([k|k<-[0..],elem k[x^y+y^x|x<-r,y<-r]]!!)

```

Really inefficient. Tests each natural number for being a Leyland number, making an infinite list of those that are. Given an input, takes that index element of the list. Uses that only `x,y` up to 31 need to be checked for 32 bit integers.

Same length with `filter`:

```
r=[2..31]
(filter(`elem`[x^y+y^x|x<-r,y<-r])[0..]!!)

```
> 5 votes

# Answer
# Pyth, 17 bytes

0-indexed.

```
@{Sms^M_Bd^}2+2Q2

```

Try it online! (Please, keep it at 100.)

## How it works

```
@{Sms^M_Bd^}2+2Q2
@{Sms^M_Bd^}2+2Q2Q  implicit filling. Input:Q

           }2+2Q    Yield the array [2,3,4,...,Q+2]
          ^     2   Cartesian square: yield all the
                    pairs formed by the above array.
   m     d          Map the following to all of those pairs (e.g. [2,3]):
       _B               Create [[2,3],[3,2]]
     ^M                 Reduce by exponent to each array:
                        create [8,9]
    s                   Sum:   17     (Leyland number generated)
  S                 Sort the generated numbers
 {                  Remove duplicate
@                Q  Find the Q-th element.

```

## Slower version

1-indexed.

```
e.ffqZs^M_BT^}2Z2

```

Try it online! (Please, keep it at 3.)
> 4 votes

# Answer
# MATLAB, 58 bytes

1-indexed

```
n=input('');[A B]=ndgrid(2:n+9);k=A.^B;x=unique(k'+k);x(n)

```

`unique` in MATLAB flattens and sorts the matrix.

---

Thanks for help to @FryAmTheEggman and @flawr.
> 4 votes

# Answer
# Husk, ~~13~~ 12 bytes

```
!uΞ´Ṫ§+^`^tN

```

Try it online!

~~Tied with MATL, with a similar method.~~

-1 byte from Zgarb!

## Explanation

```
!uΞ´Ṫ§+^`^tN
           N list of all natural numbers
          t  tail: remove 1
   ´         double: f x = f x x
    Ṫ        cartesian product with the following function
     §       fork: f g h x y = f (g x y) (h x y)
       ^     x^y
      +      plus
        `    reverse: f x y = f y x
        `^   y^x
  Ξ          merge all results together
 u           uniquify
!            take element at input index

```
> 4 votes

# Answer
## 05AB1E, ~~20~~ 19 bytes

0-indexed

```
ÝÌ2ãvyÂ`ms`m+}){Ù¹è

```

**Explained**

```
ÝÌ                     # range(2,N+2)
  2ã                   # get all pairs of numbers in the range
    v                  # for each pair
     yÂ`ms`m+          # push x^y+y^x
             }         # end loop
              ){Ù      # wrap to list, sort and remove duplicates
                 ¹è    # get Nth element of list

```

Try it online

Saved 1 byte thanks to @Adnan
> 3 votes

# Answer
# Mathematica, ~~60~~ ~~48~~ 40 bytes

```
(Union@@Array[#^#2+#2^#&,{#,#},2])[[#]]&

```

Uses one-based indexing. `Union` is used by applying it between each row of the 2D matrix created by the `Array`. There, `Union` will flatten the 2D matrix into a list while also removing any duplicates and placing the values in sorted order.

Saved 8 bytes thanks to @LLlAMnYP.

## Usage
> 3 votes

# Answer
## PowerShell v2+, ~~84~~ ~~73~~ 68 bytes

```
(2..30|%{2..($x=$_)|%{"$x*"*$_+'1+'+"$_*"*$x+1|iex}}|sort)[$args[0]]

```

*Saved 11 bytes thanks to @Neil ... saved additional 5 bytes by reorganizing how the `iex` expression is evaluated.*

Naïve method, we simply double-for loop from `x=2..30` and `y=2..x`. Each loop we put `x^y + y^x` on the pipeline. The `30` was chosen experimentally to ensure that we covered all cases less than `2^31-1` ;-). We pipe those to `Sort-Object` to order them ascending. Output is zero-indexed based on the input `$args[0]`.

Yes, there are a *lot* of extraneous entries generated here -- this algorithm actually generates 435 Leyland numbers -- but things above index `81` are not guaranteed to be accurate and in order (there may be some that are skipped).

### Examples

```
PS C:\Tools\Scripts\golfing> .\leyland-numbers.ps1 54
14352282

PS C:\Tools\Scripts\golfing> .\leyland-numbers.ps1 33
178478

PS C:\Tools\Scripts\golfing> .\leyland-numbers.ps1 77
1073792449

```
> 2 votes

# Answer
## JavaScript (Firefox 42-57), 94 bytes

```
n=>[for(x of Array(32).keys())for(y of Array(x+1).keys())if(y>1)x**y+y**x].sort((x,y)=>x-y)[n]

```

Needs Firefox 42 because it uses both array comprehensions and exponentiation (`[for(..of..)]` and `**`).
> 2 votes

# Answer
## Python 3, ~~76~~ 69 bytes

```
r=range(2,32);f=lambda n:sorted({x**y+y**x for x in r for y in r})[n]

```

0-indexed.

https://repl.it/C2SA
> 2 votes

# Answer
# Jelly, 14 bytes

2 bytes thanks to Dennis.

```
R‘*€¹$+Z$FṢQị@

```

Try it online! (Takes ~ 1s for 82 for me) (O(n^2) time)

### Original 16-byte answer

```
2r30*€¹$+Z$FṢQị@

```

Try it online! (Takes \< 1s for me) (Constant time)
> 2 votes

# Answer
# Bash + GNU utilities, 63

```
printf %s\\n x={2..32}\;y={2..32}\;x^y+y^x|bc|sort -nu|sed $1!d

```

1-based indexing. It looks like this is pretty much the same approach as @TimmyD's answer. Instead of nested loops, bash brace expansion is used to generate arithmetic expressions that are piped to `bc` for evaluation.

Ideone.
> 2 votes

# Answer
# Perl 6,  ~~60 58~~  56 bytes

```
~~{sort(keys bag [X[&({$^a**$^b+$b**$a})]] (2..$_+2)xx 2)[$_]}
{sort(keys set [X[&({$^a**$^b+$b**$a})]] (2..$_+2)xx 2)[$_]}
{sort(unique [X[&({$^a**$^b+$b**$a})]] (2..$_+2)xx 2)[$_]}
{squish(sort [X[&({$^a**$^b+$b**$a})]] (2..$_+2)xx 2)[$_]}~~
{squish(sort [X[&({$^a**$^b+$b**$a})]] (2..31)xx 2)[$_]}
{squish(sort [X[&({$^a**$^b+$b**$a})]] 2..31,2..31)[$_]}
```

### Test:

```
#! /usr/bin/env perl6
use v6.c;

my &Leyland = {squish(sort [X[&({$^a**$^b+$b**$a})]] 2..31,2..31)[$_]}

say ^14 .map: &Leyland;
time-this {Leyland 81};

sub time-this (&code) {
  my $start = now;
  my $value = code();
  printf "takes %.3f seconds to come up with $value\n", now - $start;
}

```

```
(8 17 32 54 57 100 145 177 320 368 512 593 945 1124)
takes 0.107 seconds to come up with 1996813914

```

### Explanation:

```
{
  squish( # remove repeated values
    sort
      [X[&( # cross reduce with:
        { $^a ** $^b + $b ** $a }
      )]]
        ( 2 .. $_+2 ) # ｢Range.new(2,$_+2)｣ (inclusive range)
        xx 2          # repeat list
  )[$_]
}

```
> 2 votes

# Answer
# F#, ~~117~~, 104

Welp, it's shorter than my C# answer at least.

Saved 13 bytes thanks to Reed Copsey in the F# chatroom.

```
let f n=[for x in 2I..32I do for y in 2I..32I->x**(int y)+y**(int x)]|>Seq.sort|>Seq.distinct|>Seq.nth n

```
> 2 votes

# Answer
# R, ~~58~~ 54 bytes

1-indexed. Eliminated 4 bytes by using `pryr::r` instead of `function`.

```
unique(sort(outer(2:99,2:9,pryr::f(x^y+y^x))))[scan()]

```

### Explanation

For all numbers from 2 to 99, and 2 to 9,

```
                  2:99,2:9

```

apply the function `x^y+y^x`. This generates a 98x8 matrix.

```
            outer(2:99,2:9,pryr::f(x^y+y^x))

```

Sort this matrix (coercing it to a vector):

```
       sort(outer(2:99,2:9,pryr::f(x^y+y^x)))

```

Remove all non-unique values:

```
unique(sort(outer(2:99,2:9,pryr::f(x^y+y^x))))

```

Read `n` from stdin, and fetch the `n`th number from the list:

```
unique(sort(outer(2:99,2:9,pryr::f(x^y+y^x))))[scan()]

```
> 2 votes

# Answer
# Jelly, 12 bytes

```
‘€p`*U$§QṢị@

```

Try it online!

Similar algorithm to Leaky Nun's Jelly answer but with a few improvements

## How it works

```
‘€p`*U$§QṢị@ - Main link. Takes n on the left
 €           - Yield [1, 2, ..., n]
‘            - Increment each to [2, 3, ..., n+1]
  p`         - Take the Cartesian product with itself, yielding all pairs [[2, 2], [2, 3], ..., [n+1, n+1]]
      $      - Run the previous two commands over each pair, [x, y]:
     U       -   Reverse the pair to yield [y, x]
    *        -   Raise to the power to yield [x*y, y*x]
       §     - Take the sum of each, yielding [8, 17, ..., 2(n+1)*(n+1)]]
        Q    - Deduplicate
         Ṣ   - Sort in ascending order
          ị@ - Take the nth element in this list

```
> 2 votes

# Answer
# Haskell, ~~99~~ ~~98~~ ~~96~~ ~~95~~ 94 bytes

It is probably easily outgolfed, but that was the best *I* was able to come up with.

```
import Data.List
f n|n<2=[]|n>1=sort.nub$f(n-1)++[x^n+n^x|x<-[2..n]]
g n=(f.toInteger$n+3)!!n

```
> 1 votes

# Answer
# C#, ~~141~~, 127 bytes.

Oh c#, you are such a long language.

```
n=>(from x in Enumerable.Range(2,32)from y in Enumerable.Range(2,32)select Math.Pow(x,y)+Math.Pow(y,x)).Distinct().ToList()[n];

```

This is a lambda that needs to be assigned to `delegate double del(int n);` to be run, as such:

```
delegate double del(int n);
del f=n=>(from x in Enumerable.Range(2,32)from y in Enumerable.Range(2,32)select Math.Pow(x,y)+Math.Pow(y,x)).OrderBy(q=>q).Distinct().ToList()[n];

```
> 1 votes

# Answer
# SQL (PostgreSQL 9.4), 171 bytes

Done as a prepared statement. Generate a couple of series 2 - 99, cross join them and do the equation. Densely rank the results to index them and select the first result that has the rank of the integer input.

```
prepare l(int)as select s from(select dense_rank()over(order by s)r,s from(select x^y+y^x from generate_series(2,99)x(x),generate_series(2,99)y(y))c(s))d where r=$1limit 1

```

Executed as follows

```
execute l(82)
s
-----------------
1996813914

```

This ended up running a lot quicker than I expected
> 1 votes

# Answer
# Swift 3, 138 bytes

```
import Glibc;func l(n:Int)->Int{let r=stride(from:2.0,to:50,by:1);return Int(Set(r.flatMap{x in r.map{pow(x,$0)+pow($0,x)}}).sorted()[n])}

```

**Ungolfed code**

Try it here

```
import Glibc
func l(n: Int) -> Int {
    // Create a Double sequence from 2 to 50 (because pow requires Double)
    let r = stride(from: 2.0, to: 50.0, by: 1.0)

    return Int(Set(r.flatMap {
        x in r.map {
            pow(x, $0) + pow($0, x)
        }
    }).sorted()[n])

```
> 1 votes

# Answer
# Java (JDK), 136 bytes

```
n->java.util.stream.IntStream.range(0,900).map(l->l+=Math.pow(l%30+2,l/30+2)+Math.pow(l/30+2,l%30+2)-l).sorted().distinct().toArray()[n]

```

Try it online!
> 1 votes

# Answer
# J, 29 bytes

```
<:{[:/:~@~.@,[:(^+^~)"0/~2+i.

```

Uses one-based indexing. Conversion from my Mathematica solution.

The true secret here is that I have `:(^+^~)` on my side.

## Usage

```
   f =: <:{[:/:~@~.@,[:(^+^~)"0/~2+i.
   f 7
145
   (,.f"0) >: i. 10  NB. Extra commands for formatting
 1   8
 2  17
 3  32
 4  54
 5  57
 6 100
 7 145
 8 177
 9 320
10 368

```

## Explanation

```
<:{[:/:~@~.@,[:(^+^~)"0/~2+i.  Input: n
                         2+i.  Step one
                     "0/~      Step two
              :(^+^~)          ???
<:{[:/:~@~.@,[                 Profit

```

More seriously,

```
<:{[:/:~@~.@,[:(^+^~)"0/~2+i.  Input: n
                           i.  Create the range [0, 1, ..., n-1]
                         2+    Add 2 to each
               (^+^~)"0        Create a dyad (2 argument function) with inputs x, y
                               and returns x^y + y^x
             [:        /~      Use that function to create a table using the previous range
   [:       ,                  Flatten the table into a list
         ~.@                   Take its distinct values only
     /:~@                      Sort it in ascending order
<:                             Decrement n (since J is zero-indexed)
  {                            Select the value at index n-1 from the list and return

```
> 1 votes

# Answer
**Axiom 148 bytes**

```
w(n)==(v:List INT:=[];for i in 2..31 repeat for j in i..31 repeat(a:=i^j+j^i;if a>1996813914 then break;v:=cons(a,v));v:=sort v;~index?(n,v)=>0;v.n)

```

some example

```
w(n)==
 v:List INT:=[];for i in 2..31 repeat for j in i..31 repeat
        (a:=i^j+j^i;if a>1996813914 then break;v:=cons(a,v));v:=sort v;~index?(n,v)=>0
 v.n
 (2) -> [w(i)  for i in 0..85]
    Compiling function w with type NonNegativeInteger -> Integer

    (2)
    [0, 8, 17, 32, 54, 57, 100, 145, 177, 320, 368, 512, 593, 945, 1124, 1649,
     2169, 2530, 4240, 5392, 6250, 7073, 8361, 16580, 18785, 20412, 23401,
     32993, 60049, 65792, 69632, 93312, 94932, 131361, 178478, 262468, 268705,
     397585, 423393, 524649, 533169, 1048976, 1058576, 1596520, 1647086,
     1941760, 2012174, 2097593, 4194788, 4208945, 4785713, 7861953, 8389137,
     9865625, 10609137, 14352282, 16777792, 16797952, 33554432, 33555057,
     43050817, 45136576, 48989176, 61466176, 67109540, 67137425, 129145076,
     134218457, 177264449, 244389457, 268436240, 268473872, 292475249,
     364568617, 387426321, 536871753, 774840978, 1073742724, 1073792449,
     1162268326, 1173741824, 1221074418, 1996813914, 0, 0, 0]

```

## Type: List Integer
> 1 votes

# Answer
# Perl 5, 70 + 1 (-p) = 71 bytes

```
for$x(2..32){$r{$x**$_+$_**$x}++for$x..32}$_=(sort{$a<=>$b}keys%r)[$_]

```

Try it online!
> 1 votes

# Answer
# Brachylog, 28 bytes

```
^₂g{∧{Ċ≥₁>ᵛ1&≜↔;?^ᵐ+}}ᶠ⁽o∋↙?

```

Try it online!

### How it works

```
^₂g{∧{Ċ≥₁>ᵛ1&≜↔;?^ᵐ+}}ᶠ⁽o∋↙?
^₂g                           7 -> [49]
   {∧{              }}ᶠ⁽      find first 49 outputs whose …
      Ċ≥₁>ᵛ1                  inputs are of form [X,Y],
       ≥₁                     are ordered
         >ᵛ1                  and strictly greater than 1
            &≜                force labels on input
              ↔;?             [2,3] -> [[3,2],[2,3]]
                 ^ᵐ                 -> [9, 8]
                   +                -> 17
                        o∋↙?  order outputs and take the Nth element

```
> 1 votes

# Answer
# Thunno 2, 12 bytes

```
R⁺2ẉıḲ*S;ṠUi

```

Try it online!

0-indexed.

#### Explanation

```
R⁺2ẉıḲ*S;ṠUi  # Implicit input
R⁺            # Range [2..input+1]
  2ẉ          # Cartesian power of 2
    ı   ;     # Map over each pair:
     Ḳ        #  Bifurcate: push reverse
      *       #  Exponentiation
       S      #  Sum the pair
         Ṡ    # Sort the list
          U   # And uniquify it
           i  # Index in
              # Implicit output

```
> 1 votes

# Answer
# J, ~~38~~ 31 bytes

0-indexed.

```
~~[{[:(#~~:)@/:~@,/[:(+|:)[:^/~2+i.@>:@]~~
((#~~:)/:~,/(+|:)^/~2+i.29x){~[

```

## Usage

```
>> f =: ((#~~:)/:~,/(+|:)^/~2+i.29x){~[
>> f 81
<< 1996813914

```
> 0 votes

# Answer
# Python 3, 129-\>116 bytes

I know there is a shorter python 3 answer, but I still wanted to contribute my solution.

```
t=[]
for k in range(100):a,b,q=k//10,k%10,a**b+b**a;f=lambda q:0if q in t else t.append(q);f(q)
print(sorted(t)[7:])

```

This was the best way that I could to think of to handle going through all values for x and all values for y. If anyone can golf my approach it would be appreciated
> 0 votes

# Answer
# Ruby, ~~62~~ 58 bytes

```
->n{a,*b=c=2;c+=1while(b<<a**c+c**a;c<32||32>c=a+=1);b[n]}

```

Try it online!
> 0 votes

# Answer
# APL (Dyalog), 27 bytes

```
{d⊃⍨⍵⊃⍋d←∪,∘.(*⍨+*)⍨1↓⍳1+⍵}

```

Try it online!
> 0 votes

# Answer
# Japt `-g`, 15 bytes

```
g2ôU ïÈ**Y+pXÃü

```

Try it

```
g2ôU ïÈ**Y+pXÃü
                    :Implicit input of integer U
g                   :Index into the following array
 2ôU                :  Range [2,U+2]
     ï              :  Cartesian product with itself
      È             :  Reduce each pair [X,Y]
       **Y          :    Raise X to the power of Y
          +pX       :    Add Y raised to the power of X
             Ã      :  End reduce
              ü     :  Sort & partition by value
                    :Implicit output of first element

```
> 0 votes

# Answer
# Vyxal, 77 bitsv2, 9.625 bytes

```
›Ḣ:Ẋ:ReṠUsi

```

Try it Online!

When the program is `ṠUs`.

0 indexed.

## Explained

```
›Ḣ:Ẋ:ReṠUsi
›Ḣ:Ẋ         # Cartesian product of the range [2, input + 1]
    :R       # Push a copy with each pair reversed.
      eṠ     # Zip the two lists, reduce by a ** b, and sum each pair.
        Usi  # Uniquify, sort, then get the number at the inputh index.

```

Created with the help of Luminespire.
> 0 votes

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