Sylvester's sequence

Sylvester's sequence, OEIS 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.

Create the smallest program possible that takes an n and calculates the nth term of Sylvester's Sequence. Standard input, output and loopholes apply. Since the result grows very quickly you are not expected to take any term of which the result would cause an overflow in your chosen language.

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

• What inputs are expected to be handled? The output grows quite rapidly. – Geobits Aug 26 '16 at 1:44
• @Geobits you are expected to handle as much as your language can – Sriotchilism O'Zaic Aug 26 '16 at 1:46
• Is an array which when indexed with n returns the nth number of the sequence accepted? – user6245072 Aug 26 '16 at 7:05
• @user6245072 No you must index your own arrays – Sriotchilism O'Zaic Aug 26 '16 at 12:55

C#, 144 Bytes

I used one indexing:

Golfed:

int s(int n){var a=new int[n];int b=1;for(int i=0;i<a.Length;i++){a[i]=b;b=1;a.ToList().GetRange(0,i).ForEach(o=>b*=o);a[i]=b+1;}return a[n-1];}


Ungolfed:

class SylvestersSequence
{
public int s(int n)
{
var a = new int[n];

int b = 1;

for (int i = 0; i < a.Length; i++)
{
a[i] = b;

b = 1;

a.ToList().GetRange(0, i).ForEach(o => b *= o);

a[i] = b + 1;
}

return a[n - 1];
}
}


Tests:

1 : 2
2 : 3
3 : 7
4 : 43
5 : 1807
6 : 3263443


(Things start to go a bit weird after this...)

Forth (gforth), 35 bytes

: f 2 swap 0 ?do dup 1- * 1+ loop ;


Try it online!

Explanation

1. place 2 on stack
2. loop from 0 to n-1
1. multiply top of stack by itself minus 1

Code Explanation

: f             \ Start a new word definition
2 swap        \ place 2 on the top of the stack
0 ?do         \ loop from 0 to n-1 (skip loop if n=0)
dup 1-      \ duplicate top of stack and subtract 1
*           \ multiply top two stack values
1+          \ add 1 to result
loop          \ end loop
;               \ end word definition


Japt, 9 8 bytes

@ÒZ×}gNÅ


Try it

05AB1E, 8 bytes

2λλP>}sè


Not shorter than the existing 05AB1E (legacy) answer by @Emigna, but I wanted to try out the new recursive function in the 05AB1E Elixir-rewrite.

Explanation:

2λ   }      # Define a recursive sequence function starting at a(0) = 2
λ         #  Generates a recursive infinite sequence-list [a(0), a(1), a(2), ...]
P>       #  where each a(n) takes the product + 1 of all previous results
#   i.e. [2,3,7,43,1807,3263443,10650056950807,...]
s     # Swap so the input is at the top of the stack
è    # Get the 0-indexed value of the infinite recursive sequence-list
#  i.e. 4 and [2,3,7,43,1807,3263443,10650056950807,...] → 1807


C++, 43 bytes

[&](int n){return n?f(n-1)*(f(n-1)-1)+1:2;}


Try it Online!