📜  西尔维斯特的序列

📅  最后修改于: 2021-05-04 14:08:40             🧑  作者: Mango

在数字系统中,西尔维斯特(Sylvester)的序列是一个整数序列,其中该序列的每个成员都是先前成员加一的乘积。给定正整数N。任务是打印序列的前N个成员。
由于数字可能非常大,因此请使用%10 ^ 9 + 7
例子:

Input : N = 6
Output : 2 3 7 43 1807 3263443

Input : N = 2
Output : 2 3

这个想法是运行一个循环并获取两个变量,并将它们初始化为1和2,一个变量存储到现在为止,另一个变量存储当前数字,除了第一个数字+ 1之外什么都没有,对于每一步都使用算术相乘模运算,即(a + b)%N =(a%N + b%N)%N,其中N是模数。
以下是此方法的实现:

C++
// CPP program to print terms of Sylvester's sequence
#include 
using namespace std;
#define N 1000000007
 
void printSequence(int n)
{
    int a = 1; // To store the product.
    int ans = 2; // To store the current number.
 
    // Loop till n.
    for (int i = 1; i <= n; i++) {
        cout << ans << " ";
        ans = ((a % N) * (ans % N)) % N;
        a = ans;
        ans = (ans + 1) % N;
    }
}
 
// Driven Program
int main()
{
    int n = 6;
    printSequence(n);
    return 0;
}


Java
// JAVA Code for Sylvester sequence
import java.util.*;
 
class GFG {
     
    public static void printSequence(int n)
    {
        int a = 1; // To store the product.
        int ans = 2; // To store the current number.
        int N = 1000000007;
         
        // Loop till n.
        for (int i = 1; i <= n; i++) {
           System.out.print(ans + " ");
            ans = ((a % N) * (ans % N)) % N;
            a = ans;
            ans = (ans + 1) % N;
        }
    }
 
    /* Driver program to test above function */
    public static void main(String[] args)
    {
        int n = 6;
        printSequence(n);
         
    }
}
   
// This code is contributed by Arnav Kr. Mandal.


Python
# Python Code for Sylvester sequence
 
def printSequence(n) :
    a = 1 # To store the product.
    ans = 2 # To store the current number.
    N = 1000000007
     
    # Loop till n.
    i = 1
    while i <= n :
        print ans,
        ans = ((a % N) * (ans % N)) % N
        a = ans
        ans = (ans + 1) % N
        i = i + 1
         
 
# Driver program to test above function
n = 6
printSequence(n)
 
# This code is contributed by Nikita Tiwari.


C#
// C# Code for Sylvester sequence
using System;
 
class GFG {
     
    public static void printSequence(int n)
    {
         // To store the product.
        int a = 1;
         
        // To store the current number.
        int ans = 2;
         
        int N = 1000000007;
         
        // Loop till n.
        for (int i = 1; i <= n; i++)
        {
            Console.Write(ans + " ");
            ans = ((a % N) * (ans % N)) % N;
            a = ans;
            ans = (ans + 1) % N;
        }
    }
 
    // Driver program
    public static void Main()
    {
        int n = 6;
        printSequence(n);
         
    }
}
 
// This code is contributed by vt_m.


PHP


Javascript


输出:

2 3 7 43 1807 3263443