[Question]
  [
Sylvester's sequence, [OEIS A000058](http://oeis.org/A000058), is an integer sequence defined as follows:
Each member is the product of all previous members plus one. The first member of the sequence is 2.
## Task
Create a program to calculate the nth term of Sylvester's Sequence. Standard input, output and loopholes apply.
Standard [sequence](/questions/tagged/sequence "show questions tagged 'sequence'") rules apply.
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the goal is to minimize the size of your source code as measured in bytes.
## Test Cases
You may use either zero or one indexing. (Here I use zero indexing)
```
>>0
2
>>1
3
>>2
7
>>3
43
>>4
1807
```
  
[Answer]
# [Brain-Flak](http://github.com/DJMcMayhem/Brain-Flak), ~~76~~ ~~68~~ ~~58~~ ~~52~~ 46 bytes
```
<>(()())<>{({}[()])<>({({}[()])({})}{}())<>}<>
```
[Try it online!](http://brain-flak.tryitonline.net/#code=PD4oKCkoKSk8Pnsoe31bKCldKTw-KHsoe31bKCldKSh7fSl9e30oKSk8Pn08Pg&input=NA)
Uses this relationship instead:
$$a(n) = 1+\sum^{a(n-1)-1}\_{i=0} 2i$$
which is derived from this relationship modified from that provided in the sequence:
$$a(n+1) = a(n)(a(n) - 1) + 1.$$
### Explanation
For a documentation of what each command does, please visit [the GitHub page](https://github.com/DJMcMayhem/Brain-Flak).
There are two stacks in Brain-Flak, which I shall name as Stack 1 and Stack 2 respectively.
The input is stored in Stack 1.
```
<>(()())<>             Store 2 in Stack 2.
{                      while(Stack_1 != 0){
  ({}[()])                 Stack_1 <- Stack_1 - 1;
  <>                       Switch stack.
  ({({}[()])({})}{}())     Generate the next number in Stack 2.
  <>                       Switch back to Stack 1.
}
<>                     Switch to Stack 2, implicitly print.
```
For the generation algorithm:
```
({({}[()])({})}{}())      Top <- (Top + Top + (Top-1) + (Top-1) + ... + 0) + 1
(                  )      Push the sum of the numbers evaluated in the process:
 {            }               while(Top != 0){
  ({}[()])                        Pop Top, push Top-1    (added to sum)
          ({})                    Pop again, push again  (added to sum)
                              }
               {}             Top of stack is now zero, pop it.
                 ()           Evaluates to 1 (added to sum).
```
## Alternative 46-byte version
This uses only one stack.
```
({}<(()())>){({}<({({}[()])({})}{}())>[()])}{}
```
[Try it online!](http://brain-flak.tryitonline.net/#code=KHt9PCgoKSgpKT4peyh7fTwoeyh7fVsoKV0pKHt9KX17fSgpKT5bKCldKX17fQ&input=NA)
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 5 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
Ḷß€P‘
```
This uses 0-based indexing and the definition from the challenge spec.
[Try it online!](http://jelly.tryitonline.net/#code=4bi2w5_igqxQ4oCY&input=&args=NA) or [verify all test cases](http://jelly.tryitonline.net/#code=4bi2w5_igqxQ4oCYCjjhuLbCtcW8w4figqxH&input=).
### How it works
```
Ḷß€P‘  Main link. Argument: n
Ḷ      Unlength; yield [0, ..., n - 1].
 ß€    Recursively apply the main link to each integer in that range.
   P   Take the product. This yields 1 for an empty range.
    ‘  Increment.
```
[Answer]
## [Hexagony](https://github.com/m-ender/hexagony), 27 bytes
```
1{?)=}&~".>")!@(</=+={"/>}*
```
Unfolded:
```
    1 { ? )
   = } & ~ "
  . > " ) ! @
 ( < / = + = {
  " / > } * .
   . . . . .
    . . . .
```
[Try it online!](http://hexagony.tryitonline.net/#code=MXs_KT19Jn4iLj4iKSFAKDwvPSs9eyIvPn0q&input=NA)
### Explanation
Let's consider the sequence `b(a) = a(n) - 1` and do a little rearranging:
```
b(a) = a(n) - 1
     = a(n-1)*(a(n-1)-1) + 1 - 1
     = (b(n-1) + 1)*(b(n-1) + 1 - 1)
     = (b(n-1) + 1)*b(n-1)
     = b(n-1)^2 + b(n-1)
```
This sequence is very similar but we can defer the increment to the very end, which happens to save a byte in this program.
So here is the annotated source code:
[![enter image description here](https://i.stack.imgur.com/7QTqY.png)](https://i.stack.imgur.com/7QTqY.png)  
Created with Timwi's [HexagonyColorer](https://github.com/timwi/HexagonyColorer).
And here is a memory diagram (the red triangle shows the memory pointer's initial position and orientation):
[![enter image description here](https://i.stack.imgur.com/waiLM.png)](https://i.stack.imgur.com/waiLM.png)  
Created with Timwi's [EsotericIDE](https://github.com/timwi/EsotericIDE).
The code begins on the grey path which wraps the left corner, so the initial linear bit is the following:
```
1{?)(
1      Set edge b(1) to 1.
 {     Move MP to edge N.
  ?    Read input into edge N.
   )(  Increment, decrement (no-op).
```
Then the code hits the `<` which is a branch and indicates the start (and end) of the main loop. As long as the **N** edge has a positive value, the green path will be executed. That path wraps around the grid a few times, but it's actually entirely linear:
```
""~&}=.*}=+={....(
```
The `.` are no-ops, so the actual code is:
```
""~&}=*}=+={(
""             Move the MP to edge "copy".
  ~            Negate. This is to ensure that the value is negative so that &...
   &           ...copies the left-hand neighbour, i.e. b(i).
    }=         Move the MP to edge b(i)^2 and turn it around.
      *        Multiply the two copies of b(i) to compute b(i)^2.
       }=      Move the MP back to edge b(i) and turn it around.
         +     Add the values in edges "copy" and b(i)^2 to compute
               b(i) + b(i)^2 = b(i+1).
          ={   Turn the memory pointer around and move to edge N.
            (  Decrement.
```
Once this decrementing reduces `N` to `0`, the red path is executed:
```
")!@
"     Move MP back to edge b(i) (which now holds b(N)).
 )    Increment to get a(N).
  !   Print as integer.
   @  Terminate the program.
```
[Answer]
# J, ~~18~~ ~~14~~ 12 bytes
This version thanks to randomra. I'll try to write a detailed explanation later.
```
0&(]*:-<:)2:
```
# J, 14 bytes
This version thanks to miles. Used the power adverb `^:` instead of an agenda as below. More explanation to come.
```
2(]*:-<:)^:[~]
```
# J, 18 bytes
```
2:`(1+*/@$:@i.)@.*
```
0-indexed. 
## Examples
```
   e =: 2:`(1+*/@$:@i.)@.*
   e 1
3
   e 2
7
   e 3
43
   e 4
1807
   x: e i. 10
2 3 7 43 1807 3263443 10650056950807 113423713055421862298779648 12864938683278674737956996400574416174101565840293888 1655066473245199944217466828172807675196959605278049661438916426914992848    91480678309535880456026315554816
   |: ,: x: e i. 10
                                                                                                        2
                                                                                                        3
                                                                                                        7
                                                                                                       43
                                                                                                     1807
                                                                                                  3263443
                                                                                           10650056950807
                                                                              113423713055421862298779648
                                                    12864938683278674737956996400574416174101565840293888
165506647324519994421746682817280767519695960527804966143891642691499284891480678309535880456026315554816
```
## Explanation
This is an agenda that looks like this:
```
           ┌─ 2:
           │    ┌─ 1
       ┌───┤    ├─ +
       │   └────┤           ┌─ / ─── *
── @. ─┤        │     ┌─ @ ─┴─ $:
       │        └─ @ ─┴─ i.
       └─ *
```
(Generated using `(9!:7)'┌┬┐├┼┤└┴┘│─'` then `5!:4<'e'`)
Decomposing:
```
       ┌─ ...
       │
── @. ─┤
       │
       └─ *
```
Using the top branch as a the gerund `G`, and the bottom as the selector `F`, this is:
```
e n     <=>     ((F n) { G) n
```
This uses the constant function `2:` when `0 = * n`, that is, when the sign is zero (thus `n` is zero). Otherwise, we use this fork:
```
  ┌─ 1
  ├─ +
──┤           ┌─ / ─── *
  │     ┌─ @ ─┴─ $:
  └─ @ ─┴─ i.
```
Which is one plus the following atop series:
```
            ┌─ / ─── *
      ┌─ @ ─┴─ $:
── @ ─┴─ i.
```
Decomposing further, this is product (`*/`) over self-reference (`$:`) over range (`i.`).
[Answer]
# [Perl 6](http://perl6.org), 24 bytes
```
{(2,{1+[*] @_}...*)[$_]}
```
```
{(2,{1+.²-$_}...*)[$_]}
```
## Explanation
```
# bare block with implicit parameter ｢$_｣
{
  (
    # You can replace 2 with 1 here
    # so that it uses 1 based indexing
    # rather than 0 based
    2,
    # bare block with implicit parameter ｢@_｣
    {
      1 +
      # reduce the input of this inner block with ｢&infix:<*>｣
      # ( the input is all of them generated when using a slurpy @ var )
      [*] @_
      # that is the same as:
      # ｢@_.reduce: &infix:<*>｣
    }
    # keep calling that to generate more values until:
    ...
    # forever
    *
  # get the value as indexed by the input
  )[ $_ ]
}
```
## Usage:
```
my &code = {(2,{1+[*] @_}...*)[$_]}
say code 0; # 2
say code 1; # 3
say code 2; # 7
say code 3; # 43
say code 4; # 1807
# you can even give it a range
say code 4..7;
# (1807 3263443 10650056950807 113423713055421844361000443)
say code 8;
# 12864938683278671740537145998360961546653259485195807
say code 9;
# 165506647324519964198468195444439180017513152706377497841851388766535868639572406808911988131737645185443
say code 10;
# 27392450308603031423410234291674686281194364367580914627947367941608692026226993634332118404582438634929548737283992369758487974306317730580753883429460344956410077034761330476016739454649828385541500213920807
my $start = now;
# how many digits are there in the 20th value
say chars code 20;
# 213441
my $finish = now;
# how long did it take to generate the values up to 20
say $finish - $start, ' seconds';
# 49.7069076 seconds
```
[Answer]
## Haskell, 26 bytes
```
f n|n<1=2|m<-f$n-1=1+m*m-m
```
Usage example: `f 4` -> `1807`.
[Answer]
## Java 7, ~~46~~ 42 bytes
```
int f(int n){return--n<0?2:f(n)*~-f(n)+1;}
```
Uses 0-indexing with the usual formula. I swapped `n*n-n` for `n*(n-1)` though, since Java doesn't have a handy power operator, and the `f()` calls were getting long.
[Answer]
## Haskell, 25 bytes
```
(iterate(\m->m*m-m+1)2!!)
```
[Answer]
# [S.I.L.O.S](http://github.com/rjhunjhunwala/S.I.L.O.S), 60 bytes
```
readIO 
p = 2
lblL
r = p
r + 1
p * r
i - 1
if i L
printInt r
```
[Try it online!](http://silos.tryitonline.net/#code=cmVhZElPIApwID0gMgpsYmxMCnIgPSBwCnIgKyAxCnAgKiByCmkgLSAxCmlmIGkgTApwcmludEludCBy&input=&args=NA)
Port of [my answer in C](https://codegolf.stackexchange.com/a/91162/48934).
[Answer]
# [Oasis](http://github.com/Adriandmen/Oasis), 4 bytes
Probably my last language from the golfing family! ~~Non-competing, since the language postdates the challenge.~~
Code:
```
²->2
```
Alternative solution thanks to *Zwei*:
```
<*>2
```
Expanded version:
```
a(n) = ²->
a(0) = 2
```
Explanation:
```
²    # Stack is empty, so calculate a(n - 1) ** 2.
 -   # Subtract, arity 2, so use a(n - 1).
  >  # Increment by 1.
```
Uses the **CP-1252** encoding. [Try it online!](http://oasis.tryitonline.net/#code=wrItPjI&input=&args=NQ)
[Answer]
# [Brain-Flak](https://github.com/DJMcMayhem/Brain-Flak), ~~158~~ 154 bytes
**Leaky Nun has me beat [here](https://codegolf.stackexchange.com/a/91157/56656)**
```
({}<(()())>){({}[()]<<>(())<>([]){{}<>({}<<>(({}<>))><>)<>({<({}[()])><>({})<>}{})<>{}([])}{}<>({}())([]){{}({}<>)<>([])}{}<>>)}{}([][()]){{}{}([][()])}{} 
```
[Try it Online!](http://brain-flak.tryitonline.net/#code=KHt9PCgoKSgpKT4peyh7fVsoKV08PD4oKCkpPD4oW10pe3t9PD4oe308PD4oKHt9PD4pKT48Pik8Pih7PCh7fVsoKV0pPjw-KHt9KTw-fXt9KTw-e308Pjw-KFtdKX17fTw-KHt9KCkpKFtdKXt7fSh7fTw-KTw-KFtdKX17fTw-Pil9e30oW11bKCldKXt7fXt9KFtdWygpXSl9e30&input=)
## Explanation
Put a two under the input a(0)
```
({}<(()())>) 
```
While the input is greater than zero subtract one from the input and...
```
{
({}[()]
```
Silently...
```
<
```
Put one on the other stack to act as a catalyst for multiplication
 <>(())<>
While the stack is non-empty
```
 ([])
 {
  {}
```
Move the top of the list over and copy
```
  <>({}<<>(({}<>))><>)
```
Multiply the catalyst by the copy
```
  <>({<({}[()])><>({})<>}{})<>{}
  ([])
 }
 {}
```
Add one
```
 <>({}())
```
Move the sequence back to the proper stack
```
 ([])
 {
 {}
 ({}<>)<>
 ([])
 }
 {}
 <>
>)
}{}
```
Remove all but the bottom item (i.e. the last number created)
```
([][()])
{
{}
{}
([][()])
}
{}
```
[Answer]
# C, 32 bytes
```
f(n){return--n?f(n)*~-f(n)+1:2;}
```
Uses 1-based indexing. Test it on [Ideone](http://ideone.com/v1l893).
[Answer]
# [Actually](http://github.com/Mego/Seriously), 9 bytes
```
2@`rΣτu`n
```
[Try it online!](http://actually.tryitonline.net/#code=MkBgcs6jz4R1YG4&input=NA)
Uses this relationship instead:
![formula](https://i.stack.imgur.com/ulqUV.gif)
which is derived from this relationship modified from that provided in the sequence:
`a(n+1) = a(n) * (a(n) - 1) + 1`.
[Answer]
## R,  44 42 41 bytes
2 bytes save thanks to JDL
1 byte save thanks to user5957401 
```
f=function(n)ifelse(n,(a=f(n-1))^2-a+1,2)
```
[Answer]
# Python, ~~38~~ 36 bytes
**2 bytes thanks to Dennis.**
```
f=lambda n:0**n*2or~-f(n-1)*f(n-1)+1
```
[Ideone it!](http://ideone.com/nHxzEn)
Uses this relationship modified from that provided in the sequence instead:
`a(n+1) = a(n) * (a(n) - 1) + 1`
### Explanation
`0**n*2` returns `2` when `n=0` and `0` otherwise, because `0**0` is defined to be `1` in Python.
[Answer]
# [K (oK)](https://github.com/JohnEarnest/ok), 12 bytes
```
{2|1+*/o'!x}
```
[Try it online!](https://tio.run/##y9bNz/7/P82q2qjGUFtLP19dsaL2f5q6oqHhfwA "K (oK) – Try It Online")
~~Blatantly stolen from~~ Port of [Adám's answer](https://codegolf.stackexchange.com/a/91380/74163).
Prints up to the first 11 elements of the sequence, after which the numbers become too big to handle.
Thanks @ngn for 6 bytes!
### How:
```
{2|1+*/o'!x} # Main function, argument x.
       o'!x  # recursively do (o) for each (') of [0..x-1] (!x)
   1+*/      # 1 + the product of the list
 2|          # then return the maximum between that product and 2.
```
[Answer]
# [Jelly](http://github.com/DennisMitchell/jelly), 7 bytes
```
²_’
2Ç¡
```
[Try it online!](http://jelly.tryitonline.net/#code=wrJf4oCZCjLDh8Kh&input=NA)
Uses this relationship provided in the sequence instead: `a(n+1) = a(n)^2 - a(n) + 1`
### Explanation
```
2Ç¡   Main chain, argument in input
2     Start with 2
  ¡   Repeat as many times as the input:
 Ç        the helper link.
²_’   Helper link, argument: z
²     z²
  ’   z - 1
 _    subtraction, yielding z² - (z-1) = z² - z + 1
```
[Answer]
# [Cheddar](http://cheddar.vihan.org/), 26 bytes
```
n g->n?g(n-=1)**2-g(n)+1:2
```
[Try it online!](http://cheddar.tryitonline.net/#code=biBnLT5uP2cobi09MSkqKjItZyhuKSsxOjI&input=NA)
Pretty idiomatic.
## Explanation
```
n g ->    // Input n, g is this function
  n ?     // if n is > 1
    g(n-=1)**2-g(n)+1   // Do equation specified in OEIS
  : 2     // if n == 0 return 2
```
[Answer]
# CJam, 10 bytes
```
2{_(*)}ri*
```
Uses 0-based indexing. [Try it online!](http://cjam.tryitonline.net/#code=NXsKICAgIDJ7XygqKX1yaSoKTn0q&input=MAoxCjIKMwo0)
[Answer]
# [05AB1E](http://github.com/Adriandmen/05AB1E), 7 bytes
```
2sFD<*>
```
**Explained**
Uses zero-based indexing.
```
2         # push 2 (initialization for n=0)
 sF       # input nr of times do
   D<*    # x(x-1)
      >   # add 1
```
[Try it online!](http://05ab1e.tryitonline.net/#code=MnNGRDwqPg&input=NA)
[Answer]
# R, ~~50 46~~ 44 bytes
```
    n=scan();v=2;if(n)for(i in 1:n){v=v^2-v+1};v
```
Rather than tracking the whole sequence, we just keep track of the product, which follows the given quadratic update rule as long as ~~n>1~~ n>0. (This sequence uses the "start at ~~one~~ zero" convention)
Using the start at zero convention saves a couple of bytes since we can use if(n) rather than if(n>1)
[Answer]
## [Jellyfish](https://github.com/iatorm/jellyfish/blob/master/doc.md), 13 bytes
```
p
\Ai
&(*
><2
```
[Try it online!](http://jellyfish.tryitonline.net/#code=cApcQWkKJigqCj48Mg&input=NA)
### Explanation
Let's start from the bottom up:
```
(*
<
```
This is a hook, which defines a function `f(x) = (x-1)*x`.
```
&(*
><
```
This composes the previous hook with the increment function so it gives us a function `g(x) = (x-1)*x+1`.
```
\Ai
&(*
><
```
Finally, this generates a function `h` which is an iteration of the previous function `g`, as many times as given by the integer input.
```
\Ai
&(*
><2
```
And finally, we apply this iteration to the initial value `2`. The `p` at the top just prints the result.
### Alternative (also 13 bytes)
```
p
>
\Ai
(*
>1
```
This defers the increment until the very end.
[Answer]
# Mathematica, 19 bytes
```
Nest[#^2-#+1&,2,#]&
```
---
Or 21 bytes:
```
Array[#0,#,0,1+1##&]&
```
[Answer]
# Prolog, 49 bytes
```
a(0,2).
a(N,R):-N>0,M is N-1,a(M,T),R is T*T-T+1.
```
[Answer]
# SILOS 201 bytes
```
readIO 
def : lbl
set 128 2
set 129 3
j = i
if j z
print 2
GOTO e
:z
j - 1
if j Z
print 3
GOTO e
:Z
i - 1
:a
a = 127
b = 1
c = 1
:b
b * c
a + 1
c = get a
if c b
b + 1
set a b
i - 1
if i a
printInt b
:e
```
Feel free to [try it online!](http://silos.tryitonline.net/#code=cmVhZElPIApkZWYgOiBsYmwKc2V0IDEyOCAyCnNldCAxMjkgMwpqID0gaQppZiBqIHoKcHJpbnQgMgpHT1RPIGUKOnoKaiAtIDEKaWYgaiBaCnByaW50IDMKR09UTyBlCjpaCmkgLSAxCjphCmEgPSAxMjcKYiA9IDEKYyA9IDEKOmIKYiAqIGMKYSArIDEKYyA9IGdldCBhCmlmIGMgYgpiICsgMQpzZXQgYSBiCmkgLSAxCmlmIGkgYQpwcmludEludCBiCjpl&input=&args=NA)
[Answer]
# [Red](http://www.red-lang.org), ~~55 49 45~~ 39 bytes
```
func[n][x: 2 loop n[x: x * x - x + 1]x]
```
[Try it online!](https://tio.run/##K0pN@R@UmhIdy5Vm9T@tNC85Oi82usJKwUghJz@/QCEPxK5Q0AJiXSDWVjCMrYj9X1CUmVeikKZgwAVjGcJZRnCWMZxl8h8A "Red – Try It Online")
* *-6 thanks to Galen Ivanov*
* *-4 thanks to Pedro Maimere*
* *-6 thanks to 9214*
This is the first real thing I wrote in Red. You have been warned.
[Answer]
# C, 46 bytes
```
s(n,p,r){for(p=r=2;n-->0;p*=r)r=p+1;return r;}
```
[Ideone it!](http://ideone.com/cDMGB6)
Uses `p` as the temporary storage of the product.
Basically, I defined two sequences `p(n)` and `r(n)`, where `r(n)=p(n-1)+1` and `p(n)=p(n-1)*r(n)`.
`r(n)` is the required sequence.
[Answer]
# C, ~~43~~, ~~34~~, 33 bytes
1-indexed:
```
F(n){return--n?n=F(n),n*n-n+1:2;}
```
Test main:
```
int main() {
  printf("%d\n", F(1));
  printf("%d\n", F(2));
  printf("%d\n", F(3));
  printf("%d\n", F(4));
  printf("%d\n", F(5));
}
```
[Answer]
# [Brachylog](http://github.com/JCumin/Brachylog), 13 bytes
```
0,2|-:0&-y+*+
```
[Try it online!](http://brachylog.tryitonline.net/#code=MCwyfC06MCYteSsqKw&input=NA&args=Wg)
Uses this relationship instead:
![formula](https://i.stack.imgur.com/ulqUV.gif)
which is derived from this relationship modified from that provided in the sequence:
`a(n+1) = a(n) * (a(n) - 1) + 1`.
[Answer]
## [Labyrinth](http://github.com/mbuettner/labyrinth), 18 bytes
*Credits to Sp3000 who found the same solution independently.*
```
?
#
)}"{!@
* (
(:{
```
[Try it online!](http://labyrinth.tryitonline.net/#code=PwojCil9InshQAoqICgKKDp7&input=NA)
]