[Question]
  [
Since Euclid, we have known that there are infinitely many primes. The argument is by contradiction: If there are only finitely many, let's say \$p\_1,p\_2,...,p\_n\$, then surely \$m:=p\_1\cdot p\_2\cdot...\cdot p\_n+1\$ is not divisible by any of these primes, so its prime factorization must yield a new prime that was not in the list. So the assumption that only finitely primes exist is false.
Now let's assume that \$2\$ is the only prime. The method from above yields \$2+1=3\$ as a new (possible) prime. Applying the method again yields \$2\cdot 3+1=7\$, and then \$2\cdot 3\cdot 7+1=43\$, then \$2\cdot 3\cdot 7\cdot 43+1=13\cdot 139\$, so both \$13\$ and \$139\$ are new primes, etc. In the case where we get a composite number, we just take the least new prime. This results in [A000945](http://oeis.org/A000945).
### Challenge
Given a prime \$p\_1\$ and an integer \$n\$ calculate the \$n\$-th term \$p\_n\$ of the sequence defined as follows:
$$p\_n := \min(\operatorname{primefactors}(p\_1\cdot p\_2\cdot ... \cdot p\_{n-1} + 1))$$
These sequences are known as *Euclid-Mullin*-sequences.
### Examples
For \$p\_1 = 2\$:
```
1 2
2 3
3 7
4 43
5 13
6 53
7 5
8 6221671
9 38709183810571
```
For \$p\_1 = 5\$ ([A051308](http://oeis.org/A051308)):
```
1 5
2 2
3 11
4 3
5 331
6 19
7 199
8 53
9 21888927391
```
For \$p\_1 = 97\$ ([A051330](http://oeis.org/A051330))
```
1 97
2 2
3 3
4 11
5 19
6 7
7 461
8 719
9 5
```
  
[Answer]
# JavaScript (ES6), ~~45~~ 44 bytes
Takes input as `(n)(p1)`, where \$n\$ is 0-indexed.
```
n=>g=(p,d=2)=>n?~p%d?g(p,d+1):--n?g(p*d):d:p
```
[Try it online!](https://tio.run/##TYxRC4IwFEbf@xX3wWA3p5RQkTZ96ldE4HBqC9kuGr2M9dfXfOvp4xwO30t@5NLNmt6ZsaoPgwhG1KNgxJUoUNSm@dJWNeMq0gOWWWZW2CksVUmhuhccjhwu50c@2PkmuycjEDW4DUAUTIOAfQUarnCKk6YInTWLnfp8siNrJUsceZ447TGmiRuYRkboW6zixX8bhcfwAw "JavaScript (Node.js) – Try It Online")
### Commented
```
n =>                // n = 0-based index of the requested term
  g = (             // g is a recursive function taking:
    p,              //   p = current prime product
    d = 2           //   d = current divisor
  ) =>              //
    n ?             // if n is not equal to 0:
      ~p % d ?      //   if d is not a divisor of ~p (i.e. not a divisor of p + 1):
        g(p, d + 1) //     increment d until it is
      :             //   else:
        --n ?       //     decrement n; if it's still not equal to 0:
          g(p * d)  //       do a recursive call with the updated prime product
        :           //     else:
          d         //       stop recursion and return d
    :               // else:
      p             //   don't do any recursion and return p right away
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 6 bytes
This produces and infinite output stream. 
```
λλP>fW
```
[Try it online!](https://tio.run/##yy9OTMpM/f//3O5Di8/tDrBLC///34jLDAA "05AB1E – Try It Online") (link includes a slightly modified version, `λ£λP>fW`, which instead outputs the first \$n\$ terms)
### Explanation
Very straightforward. Given \$p\_1\$ and \$n\$, the program does the following:
* Starts with \$p\_1\$ as an initial parameter for the infinite stream (which is generated using the first `λ`) and begins a *recursive environment* which generates a new term after each interation and appends it to the stream.
* The second `λ`, now being used *inside* the recursive environment, changes its functionality: Now, it retrieves all previously generated elements (i.e. the list \$[\lambda\_0, \lambda\_1, \lambda\_2, \ldots, \lambda\_{n-1}]\$), where \$n\$ represents the current iteration number.
* The rest is trivial: `P` takes the product (\$\lambda\_0\lambda\_1\lambda\_2 \cdots \lambda\_{n-1}\$), `>` adds one to this product, and `fW` retrieves the minimum prime factor.
[Answer]
# [J](http://jsoftware.com/), 15 bytes
-10 bytes thanks to miles!
Returning the sequence up to n (zero-indexed) – thanks to [@miles](https://codegolf.stackexchange.com/users/6710/miles)
```
(,0({q:)1+*/)^:
```
[Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/NXQMNKoLrTQNtbX0NeOs/mtyKXClJmfkK1gopCkYQZiWQKYpQtTS/D8A "J – Try It Online")
# [J](http://jsoftware.com/), 25 bytes
Returns the `n` th item
```
_2{((],0{[:q:1+*/@])^:[])
```
[Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/442qNTRidQyqo60KrQy1tfQdYjXjrKJjNf9rcilwpSZn5CtYKKQpGEGYlkCmKULU0vw/AA "J – Try It Online")
[Answer]
# [Python 2](https://docs.python.org/2/), 56 bytes
```
i=input();k=1
while 1:
 k*=i;print i;i=2
 while~k%i:i+=1
```
[Try it online!](https://tio.run/##K6gsycjPM/r/P9M2M6@gtERD0zrb1pCrPCMzJ1XB0IpLIVvLNtO6oCgzr0Qh0zrT1ohLASxXl62aaZWpbWv4/7@lOQA "Python 2 – Try It Online")
---
## Commented
```
i=input() # the initial prime
k=1       # the product of all previous primes
while 1:  # infinite loop
 k*=i     # update the product of primes
 print i  # output the last prime
 i=2      # starting at two ...
 while~k%i: # find the lowest number that divides k+1
  i+=1
            # this our new prime
```
[Try it online!](https://tio.run/##XY/RagMhEEXf/YoLJdA2sLB5CQ34MTaa7rDGER2z9CW/vtG4pZB5GRjPXM/EX5k4HNaVNIVY5P0Db5DJgQIJGY@Y6OrUrEf06q8xsS1nAV9gfIPcjbjkTme1TOQdxlPDKVxaloNnjgrzp6YtqERr6vwlb4toPQiogVykqj1Bb7JsTiB9@HPKYpJQ@IGp2MIYhkHhaXGfd3SqRJWwPYEXVzNCuX67VCd1w9KNrMuY96MCaK9b@692MuVqkRDc0n9f16/jAw "Python 2 – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 8 bytes
```
P‘ÆfṂṭµ¡
```
A full program (using zero indexing) accepting \$P\_0\$ and \$n\$ which prints a Jelly representation of the list of \$P\_0\$ to \$P\_n\$ inclusive. (As a dyadic Link, with `n=0` we'll be given back an integer, not a list.)
**[Try it online!](https://tio.run/##AR4A4f9qZWxsef//UOKAmMOGZuG5guG5rcK1wqH///81/zg "Jelly – Try It Online")**
### How?
```
P‘ÆfṂṭµ¡ - Link: integer, p0; integer n
      µ¡ - repeat the monadic chain to the left n times, starting with x=p0:
P        -   product of x (p0->p0 or [p0,...,pm]->pm*...*p0)
 ‘       -   increment
  Æf     -   prime factors
    Ṃ    -   minimum
     ṭ   -   tack
         - implicit print
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 8 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
GDˆ¯P>fß
```
First input is \$n\$, second is prime \$p\$.
[Try it online](https://tio.run/##yy9OTMpM/f/f3eV026H1AXZph@f//2/GZQoA) or [very some more test cases](https://tio.run/##yy9OTMpM/V9m4Vppr6SQmJeioGTvB2Q9apsEZFX6/Xd3Od12aH2AXdrh@f9rdQ5t@R9tpGOqY2keCwA) (test suite lacks the test cases for \$n\geq9\$, because for \$p=2\$ and \$p=5\$ the builtin `f` takes too long).
**Explanation:**
```
G         # Loop (implicit input) n-1 amount of times:
 Dˆ       #  Add a copy of the number at the top of the stack to the global array
          #  (which will take the second input p implicitly the first iteration)
   ¯      #  Push the entire global array
    P     #  Take the product of this list
     >    #  Increase it by 1
      f   #  Get the prime factors of this number (without counting duplicates)
       ß  #  Pop and only leave the smallest prime factor
          # (after the loop: implicitly output the top of the stack as result)
```
[Answer]
# [Japt](https://github.com/ETHproductions/japt), ~~12~~ 11 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
Struggled to get this one right so may have missed something that can be golfed.
Takes `n` as the first input and `p1`, as a singleton array, as the second. Returns the first `n` terms. Change `h` to `g` to return the `n`th 0-indexed term instead.
```
@Z×Ä k Î}hV
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=QFrXxCBrIM59aFY&input=OQpbOTdd)
```
@Z×Ä k Î}hV     :Implicit input of integer U=n & array V=[p1]
@               :Function taking an array as an argument via parameter Z
 Z×             :  Reduce Z by multiplication
   Ä            :  Add 1
     k          :  Prime factors
       Î        :  First element
        }       :End function
         hV     :Run that function, passing V as Z, and
                : push the result to V.
                : Repeat until V is of length U
```
[Answer]
# [Retina](https://github.com/m-ender/retina/wiki/The-Language), 56 bytes
```
,|$
$*
"$&"{~`.+¶
$$¶_
)`\b(__+?)\1*$
$.1$*
1A`
.$
\*
,
```
[Try it online!](https://tio.run/##K0otycxLNPz/X6dGhUtFi0tJRU2pui5BT/vQNi4VlUPb4rk0E2KSNOLjte01Ywy1gGr0DIHKDB0TuPRUuLhitLh0/v835TLSMQYA "Retina – Try It Online") Takes input as the number of new terms to add on the first line and the seed term(s) on the second line. Note: Gets very slow since it uses unary factorisation so it needs to create a string of the relevant length. Explanation:
```
,|$
$*
```
Replace the commas in the seed terms with `*`s and append a `*`. This creates a Retina expression for a string of length of the product of the values.
```
"$&"{
)`
```
Repeat the loop the number of times given by the first input.
```
~`.+¶
$$¶_
```
Temporarily replace the number on the first line with a `$` and prepend a `_` to the second line, then evaluate the result as a Retina program, thus appending a string of `_`s of length 1 more than the product of the values.
```
\b(__+?)\1*$
$.1$*
```
Find the smallest nontrivial factor of the number in decimal and append a `*` ready for the next loop.
```
1A`
```
Delete the iteration input.
```
.$
```
Delete the last `*`.
```
\*
,
```
Replace the remaining `*`s with `,`s.
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 54 bytes
```
f=(p,n,P=p,F=n=>-~P%n?F(n+1):n)=>--n?f(p=F(2),n,P*p):p
```
[Try it online!](https://tio.run/##Fc1BC4JAEIbhe79iDgYzuQYKUWmTN8/eI1DMjUJmB40uYn99c08fPHzwvttvO3XjSz@JuEfvvWVUI6ZmNRULX5NfvZWyQolTyoVWSKS0qFxhRuG4U8rVWzeigrNwy8zBnI932gAEFE4LuZwKieNAAJ2TyQ39fnBPbCxGsy4GolkWAl7XhjwtDRX@Dw "JavaScript (Node.js) – Try It Online")
**Ungolfed**
```
F=(p,n=2)=>            // Helper function F for finding the smallest prime factor
  p%n                  //   If n (starting at 2) doesn't divide p:
    ?F(n+1)            //     Test n+1 instead
    :n                 //   Otherwise, return n
f=(p,n,P=p)=>          // Main function f:
  --n                  //   Repeat n - 1 times:
    ?f(p=F(P+1),n,P*p) //     Find the next prime factor and update the product
    :p                 //   Return the last prime
```
[Answer]
# bash +GNU coreutils, 89 bytes
```
IFS=\*;n=$1;shift;for((;++i<n;));{ set $@ `factor $["$*+1"]|cut -d\  -f2`;};echo ${@: -1}
```
[TIO](https://tio.run/##S0oszvj/39Mt2DZGyzrPVsXQujgjM63EOi2/SEPDWls70ybPWlPTulqhOLVEQcVBISEtMbkkv0hBJVpJRUvbUCm2Jrm0REE3JUZBQTfNKMG61jo1OSNfQaXawUpB17D2////5v9NAQ)
[Answer]
# Ruby 2.6, 51 bytes
```
f=->s,n{[s,l=(2..).find{|d|~s%d<1}][n]||f[l*s,n-1]}
```
`(2..)`, the infinite range starting from 2, isn't supported on TIO yet.
This is a recursive function that takes a starting value `s` (can be a prime or composite), returns it when n=0 (edit: note that this means it's zero-indexed), returns the least number `l` that's greater than 1 and divides `-(s+1)` when n=1, and otherwise recurses with `s=l*s` and `n=n-1`.
[Answer]
# [APL (Dyalog Extended)](https://github.com/abrudz/dyalog-apl-extended), 15 bytes
This is a fairly simple implementation of the algorithm which uses Extended's very helpful prime factors builtin, `⍭`. [Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNrShJzUtJTfn/qKNdIe1/9aPerTqPupof9a411D48XR/IrX3Uu/hR39RHXYuAJEjZ/zQuIy5zAA "APL (Dyalog Extended) – Try It Online")
```
{⍵,⊃⍭1+×/⍵}⍣⎕⊢⎕
```
**Explanation**
```
{⍵,⊃⍭1+×/⍵}⍣⎕⊢⎕
             ⊢⎕  First get the first prime of the sequence S from input.
{         }⍣⎕    Then we repeat the code another input number of times.
     1+×/⍵       We take the product of S and add 1.
    ⍭            Get the prime factors of product(S)+1.
   ⊃             Get the first element, the smallest prime factor of prod(S)+1.
 ⍵,              And append it to S.
```
[Answer]
# [Stax](https://github.com/tomtheisen/stax), 9 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax)
```
é|G╝╓c£¼_
```
[Run and debug it](https://staxlang.xyz/#p=827c47bcd6639cac5f&i=2+7%0A5+7%0A97+6&a=1&m=2)
Takes `p0` and (zero-indexed) `n` for input. Produces `pn`.
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~54~~ 53 bytes
```
p;f(x,n){for(p=x;--n;p*=x)for(x=1;~p%++x;);return x;}
```
[Try it online!](https://tio.run/##HYxBCoMwEEXXeopBsCRNssiqyDQ36UZiI0I7HaLSgNijN01dfXj897wZvc@ZMYikSW7hFQW7hMYQ8tkl@QfJWfxwq1RCifG@rJEg4Z6f/URCbnU10QJsNRDW1ex7CqJph0bDia0sqDRAEDiwCARX6MooJYFjEY8vtMONikAagjhKsoh77i5fHx79OGfz/gE "C (gcc) – Try It Online")
*-1 byte thanks to [ceilingcat](https://codegolf.stackexchange.com/users/52904/ceilingcat)*
[Answer]
# [Perl 6](https://github.com/nxadm/rakudo-pkg), ~~33~~ 32 bytes
*-1 byte thanks to nwellnhof*
```
{$_,{1+(2...-+^[*](@_)%%*)}...*}
```
[Try it online!](https://tio.run/##K0gtyjH7n1upoJamYKvwv1olXqfaUFvDSE9PT1c7LlorVsMhXlNVVUuzFiiiVfu/OLFSIU3DSDM6zjzWmgvCMwXyLOA8S3Mg1zLW@j8A "Perl 6 – Try It Online")
Anonymous code block that takes a number and returns a lazy list.
### Explanation:
```
{                              }  # Anonymous codeblock
                           ...*   # That returns an infinite list
 $_,                              # Starting with the input
    {                     }       # Where each element is
     1+(2...             )          # The first number above 2
                      %%*           # That cleanly divides
               [*](@_)                # The product of all numbers so far
            -+^                       # Plus one
```
[Answer]
# [Pari/GP](http://pari.math.u-bordeaux.fr/), 45 bytes
```
(p,n)->s=p;for(i=2,n,s*=p=divisors(s+1)[2]);p
```
[Try it online!](https://tio.run/##FcoxCsMwDEbhq/x0slp5iKGUkioXMR4CwUWLI6zSqXd3k@XBg8/WrvFto0JGMG4UFxeb696DSuLGfhWTTb/qe/fgt4lyKjTbyKdpEEyMJ8O6tk/IxmgFF8TlSA3nEtEPhldEToz7oR@ljD8 "Pari/GP – Try It Online")
[Answer]
# [Haskell](https://www.haskell.org/), 49 bytes
```
g 1
g a b=b:g(a*b)([c|c<-[2..],1>mod(a*b+1)c]!!0)
```
[Try it online!](https://tio.run/##y0gszk7NyfmfpmCrEPM/XcGQK10hUSHJNskqXSNRK0lTIzq5JtlGN9pITy9Wx9AuNz8FJKxtqJkcq6hooPk/NzEzD6i1oCgzr0RBRaEkMTtVwVxBI03BSPP/v@S0nMT04v@6yQUFAA "Haskell – Try It Online")
Returns the infinite sequence as a lazy list.
### Explanation:
```
g 1                                            -- Initialise the product as 1
g a b=                                         -- Given the product and the current number
       b:                                      -- Return the current number, followed by
         g                                     -- Recursively calliong the function with
          (a*b)                                -- The new product
               (                             ) -- And get the next number as
                [c|c<-[2..],             ]!!0  -- The first number above 2
                            1>mod       c      -- That cleanly divides
                                 (a*b+1)       -- The product plus one
```
[Answer]
# [Husk](https://github.com/barbuz/Husk), 8 bytes
```
!¡ö←p→Π;
```
[Try it online!](https://tio.run/##ARwA4/9odXNr//8hwqHDtuKGkHDihpLOoDv///85N/84 "Husk – Try It Online")
For input `m`,`n` outputs the `n`-th term in the sequence starting with `m`.
Drop the initial `!` (for 7 bytes) to output the entire infinite sequence ([this link](https://tio.run/##ASEA3v9odXNr/@KGkTEw4oKB/8Khw7bihpBw4oaSzqA7////OTc) selects the first 10 elements from the infinite list).  
If both input & output are flexible enough (input: list of just the first term, output: infinite sequence) we could get down to [6 bytes](https://tio.run/##ASIA3f9odXNr/@KGkTEw4oKB/8Khw7bihpBw4oaSzqD///9bOTdd).
]