42
\$\begingroup\$

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.

Task

Create a program to calculate the nth term of Sylvester's Sequence. Standard input, output and loopholes apply.

Standard rules apply.

This is , 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
\$\endgroup\$
3
  • \$\begingroup\$ What inputs are expected to be handled? The output grows quite rapidly. \$\endgroup\$
    – Geobits
    Commented Aug 26, 2016 at 1:44
  • 1
    \$\begingroup\$ @Geobits you are expected to handle as much as your language can \$\endgroup\$
    – Wheat Wizard
    Commented Aug 26, 2016 at 1:46
  • \$\begingroup\$ TypeScript’s type system can handle unary numbers up to 999, but could also take the input as a list of base-10 digits and do math in those, but for many more bytes. Would the first be acceptable, or must I choose the second since it’s possible? \$\endgroup\$ Commented Sep 16, 2023 at 21:16

81 Answers 81

1 2
3
0
\$\begingroup\$

Perl6, 49 bytes

my &f={my @c=2;@c.push: 1+[*] @c for ^$_;@c[*-1]}

Ungolfed:

sub f($n) {
  my @sylvester = 2; # declare an array to store the previous
                     # values of the sequence
  # insert S(1) ... S(n) (n iterations)
  @sylvester.push(1 + [*] @sylvester) for 0..^$n;
  return @sylvester[* - 1]; # return last element
}
\$\endgroup\$
1
  • \$\begingroup\$ You don't need to include my&f= in these competitions, an anonymous code object is fine. \$\endgroup\$ Commented Aug 26, 2016 at 22:13
0
\$\begingroup\$

Batch, 70 bytes

@set/ap=r=2
@for /l %%i in (1,1,%1)do @set/at=p,p*=r,r=t+1
@echo %r%

Zero indexed, uses @LeakyNun's recurrence relation. Conveniently set/a works inside a for loop, because I'm not using % substitution.

\$\endgroup\$
0
\$\begingroup\$

Scala, 85 bytes (51?)

val s:Stream[BigInt]=2#::3#::s.tail.map{c=>c*c-c+1}
print(s.take(args(0).toInt).last)

3 less if I stick with an Int. The stream bit which actually does all the work is 51 bytes. The rest is just printing

Usage:

$ scala sylvester.scala 20
\$\endgroup\$
0
\$\begingroup\$

Javascript (Using external library - Enumerable) (52 bytes)

n=>_.Sequence(n,(i,a)=>_.From(a).Product()+1).Last()

Link to lib: https://github.com/mvegh1/Enumerable

Code explanation: Static method on library "Sequence" will generate a sequence of elements for a count of 'n', according to the predicate accepting params "i"teration, "a"ccumulated-array. The predicate states to cast the array to the library's Enumerable data-type, use the built in Product method on it, then add 1 to that value. After the sequence is generated, take the last value because the problem states to just find the 'N'th element of the sequence

enter image description here

\$\endgroup\$
0
\$\begingroup\$

Sesos, 17 bytes

Hexdump:

0000000: ae2cf0 20f8be b273d0 7d9cde a0dd3b 7e3e           .,. ...s.}....;~>

Try it online!

\$\endgroup\$
0
\$\begingroup\$

UGL, 15 bytes

cuuild@$d*u@:_o

Try it online!

\$\endgroup\$
0
\$\begingroup\$

Pyke, 9 bytes

[SOm[BhRK

Try it here!

\$\endgroup\$
0
\$\begingroup\$

Perl, 35 bytes

$a=2;$a=$a**2-$a+1 for 1..<>;say $a

Might be shorter with a recursive function but I couldn't get that to work in my few attempts

\$\endgroup\$
0
\$\begingroup\$

ForceLang, 193 bytes

Noncompeting, as for some reason I forgot to give the language's lists a len method when I first implemented them.

def s set
def l a.len()
s g goto
s n io.readnum()
s n n+1
s a []
s b 1
label 1
s n n+-1
s a[l] b+1
if n=0
g 3
s b 1
s i 0
label 2
s b b.mult a[i]
s i i+1
if i=l
g 1
g 2
label 3
io.write a[l+-1]
\$\endgroup\$
0
\$\begingroup\$

Racket 74 bytes

(define(f n(l'(2)))(if(< n 2)(reverse l)(f(- n 1)(cons(+(apply * l)1)l))))

Detailed version:

(define (f n (l '(2)))
  (if (< n 2)
      (reverse l)
      (f (- n 1) (cons (+ 1 (apply * l)) l))))

Testing:

(f 7)

Output:

'(2 3 7 43 1807 3263443 10650056950807)
\$\endgroup\$
0
\$\begingroup\$

C, 44 bytes

g(i,j){return i<2?2:(j=g(i-1,0),j*(j-1)+1);}
\$\endgroup\$
0
\$\begingroup\$

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...)

\$\endgroup\$
0
\$\begingroup\$

Forth (gforth), 35 bytes

Answer uses 0-indexing

: 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
    2. add 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
\$\endgroup\$
0
\$\begingroup\$

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.

Try it online or verify all test cases.

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
\$\endgroup\$
0
\$\begingroup\$

C++, 43 bytes

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

Try it Online!

\$\endgroup\$
1
0
\$\begingroup\$

cQuents, 9 bytes

=2:ZZ-Z+1

1-indexed.

Try it online!

Explanation

=2          first term is 2
  :         given input n, output nth term
            each term equals
   ZZ-Z+1   previous * previous - previous + 1
\$\endgroup\$
0
\$\begingroup\$

Zsh, 35 bytes

for ((A=2;n++<$1;A=A*~-A+1)):
<<<$A

Try it online!

\$\endgroup\$
0
\$\begingroup\$

JavaScript, 28 bytes

A function. Expect a number as input.

f=n=>n?f(n-1)*(f(n-1)-1)+1:2

Using the formula a[n] = a[n-1] * ( a[n-1] - 1 ) + 1.

Explanation. The ungolfed and commented version:

var f = (n) => {                 // Define a function
  n ?                            // If n is not zero...
                                 // (non-negative numbers and TRUE booleans are 
                                 // equivalent in JavaScript)
    f(n-1) * (f(n-1) - 1) + 1    // Then use the recurrence formula.
    :                            // Else, if n is zero...
    2                            // Return 2 to end recurrence.
}
\$\endgroup\$
2
  • \$\begingroup\$ In case you didn't know, you can use Try It Online to generate formatted answers (click link icon at the top). \$\endgroup\$
    – Dingus
    Commented Feb 15, 2021 at 12:07
  • \$\begingroup\$ @Dingus Unfortunately I'm in a region which can't access TIO. Definitely I know that website :D \$\endgroup\$
    – atzlt
    Commented Feb 15, 2021 at 12:08
0
\$\begingroup\$

MMIX, 24 bytes (6 instrs)

Works mod \$2^{64}\$. One-based indexing.

(jxd)

00000000: e3ff0001 2301ff01 1affff01 27000001  ẉ”¡¢#¢”¢ȷ””¢'¡¡¢
00000010: 5b00fffd f8020000                    [¡”’ẏ£¡¡

Disassembly:

sylv    SET  $255,1         // b(1)=1 
0H      ADDU $1,$255,$1     // loop: a(n) = b(n) + 1
        MULU $255,$255,$1   // b(n+1) = a(n) * b(n)
        SUBU $0,$0,1
        PBNZ $0,0B          // if(--i) goto loop
        POP  2,0            // return a
\$\endgroup\$
0
\$\begingroup\$

Fig, \$5\log_{256}(96)\approx\$ 4.116 bytes

}rMXr

Try it online!

Port of Jelly. Link contains extra code to run all test cases.

}rMXr
    r # Range [0, n)
  MX  # Map by this function
 r    # Product
}     # Increment
\$\endgroup\$
0
\$\begingroup\$

Go, 59 bytes, int only

func f(n int)int{if n<1{return 2}
k:=f(n-1)
return k*k-k+1}

Attempt This Online!

Go, 126 bytes, arbitrarily large outputs

import."math/big"
func f(n int)*Int{i,l:=NewInt,new(Int)
if n<1{return i(2)}
k:=f(n-1)
return l.Add(l.Sub(l.Mul(k,k),k),i(1))}

Attempt This Online!

\$\endgroup\$
1 2
3

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.