Sylvester’s sequence
Last Updated :
16 Feb, 2023
In number system, Sylvester’s sequence is an integer sequence in which each member of the sequence is the product of the previous members, plus one. Given a positive integer N. The task is to print the first N member of the sequence.
Since numbers can be very big, use %10^9 + 7.
Examples:
Input : N = 6
Output : 2 3 7 43 1807 3263443
Input : N = 2
Output : 2 3
The idea is to run a loop and take two variables and initialise them as 1 and 2, one to store the product till now and other to store the current number which is nothing but the first number + 1 and for each step multiply both using arithmetic modular operation i.e (a + b)%N = (a%N + b%N)%N where N is a modular number.
Below is the implementation of this approach:
C++
#include <bits/stdc++.h>
using namespace std;
#define N 1000000007
void printSequence( int n)
{
int a = 1;
int ans = 2;
for ( int i = 1; i <= n; i++) {
cout << ans << " " ;
ans = ((a % N) * (ans % N)) % N;
a = ans;
ans = (ans + 1) % N;
}
}
int main()
{
int n = 6;
printSequence(n);
return 0;
}
|
Java
import java.util.*;
class GFG {
public static void printSequence( int n)
{
int a = 1 ;
int ans = 2 ;
int N = 1000000007 ;
for ( int i = 1 ; i <= n; i++) {
System.out.print(ans + " " );
ans = ((a % N) * (ans % N)) % N;
a = ans;
ans = (ans + 1 ) % N;
}
}
public static void main(String[] args)
{
int n = 6 ;
printSequence(n);
}
}
|
Python
def printSequence(n) :
a = 1
ans = 2
N = 1000000007
i = 1
while i < = n :
print ans,
ans = ((a % N) * (ans % N)) % N
a = ans
ans = (ans + 1 ) % N
i = i + 1
n = 6
printSequence(n)
|
C#
using System;
class GFG {
public static void printSequence( int n)
{
int a = 1;
int ans = 2;
int N = 1000000007;
for ( int i = 1; i <= n; i++)
{
Console.Write(ans + " " );
ans = ((a % N) * (ans % N)) % N;
a = ans;
ans = (ans + 1) % N;
}
}
public static void Main()
{
int n = 6;
printSequence(n);
}
}
|
PHP
<?php
$N = 1000000007;
function printSequence( $n )
{
global $N ;
$a = 1;
$ans = 2;
for ( $i = 1; $i <= $n ; $i ++)
{
echo $ans , " " ;
$ans = (( $a % $N ) * ( $ans % $N )) % $N ;
$a = $ans ;
$ans = ( $ans + 1) % $N ;
}
}
$n = 6;
printSequence( $n );
?>
|
Javascript
<script>
let N = 1000000007;
function printSequence(n)
{
let a = 1;
let ans = 2;
for (let i = 1; i <= n; i++)
{
document.write(ans + " " );
ans = ((a % N) * (ans % N)) % N;
a = ans;
ans = (ans + 1) % N;
}
}
let n = 6;
printSequence(n);
</script>
|
Output:
2 3 7 43 1807 3263443
Time complexity : O(n)
Auxiliary Space : O(1)
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...