给定整数N ,任务是打印Euclid-Mullin序列的前N个元素。
Euclid-Mullin序列是素数序列,其中每个元素是一个的最小素数因子加上所有较早元素的乘积。
该序列以古希腊数学家Euclid命名。
例子:
Input: N = 14
Output: 2 3 7 43 13 53 5 6221671 38709183810571 139 2801 11 17 5471
方法: Euclid-Mullin序列是质数序列,其中序列的第n个数是:
因此,我们将运行一个从1到N的循环,并采用一个初始为1的变量乘积,其中将包含所有先前元素的乘积。然后,我们将在O(sqrt(n))时间中找到(1 +乘积)的最小素因数,并打印数字。请注意,由于乘积太大并且找到最小的素因数需要花费大量时间,因此代码无法在第14个元素后打印数字。
下面是上述方法的实现:
Java
// Java implementation of the approach
import java.math.BigInteger;
class GFG {
// Function to return the smallest prime factor of n
static BigInteger smallestPrimeFactor(BigInteger n)
{
// Initialize i = 2
BigInteger i = BigInteger.valueOf(2);
// While i <= sqrt(n)
while ((i.multiply(i)).compareTo(n) <= 0) {
// If n is divisible by i
if (n.mod(i).compareTo(BigInteger.ZERO) == 0)
return i;
// Increment i
i = i.add(BigInteger.ONE);
}
return n;
}
// Function to print the first n
// terms of the required sequence
static void solve(BigInteger n)
{
// To store the product of the previous terms
BigInteger product = BigInteger.ONE;
// Traverse the prime numbers
BigInteger i = BigInteger.ZERO;
while (i.compareTo(n) < 0) {
// Current term will be smallest prime
// factor of (1 + product of all previous terms)
BigInteger num = smallestPrimeFactor(product.add(BigInteger.ONE));
// Print the current term
System.out.print(num + " ");
// Update the product
product = product.multiply(num);
i = i.add(BigInteger.ONE);
}
}
// Driver code
public static void main(String[] args)
{
// Find the first 14 terms of the sequence
BigInteger b = BigInteger.valueOf(14);
solve(b);
}
}
Python3
# Python3 implementation of the approach
# Function to return the smallest prime factor of n
def smallestPrimeFactor(n):
# Initialize i = 2
i = 2
# While i <= sqrt(n)
while (i * i) <= n :
# If n is divisible by i
if n % i == 0:
return i
# Increment i
i += 1
return n
# Function to print the first n
# terms of the required sequence
def solve(n):
# To store the product of the previous terms
product = 1
# Traverse the prime numbers
i = 0
while i < n:
# Current term will be smallest prime
# factor of (1 + product of all previous terms)
num = smallestPrimeFactor(product + 1)
# Print the current term
print(num, end=' ')
# Update the product
product = product * num
i += 1
# Driver code
# Find the first 14 terms of the sequence
b = 14
solve(b)
# This code is contributed by divyamohan123
输出:
2 3 7 43 13 53 5 6221671 38709183810571 139 2801 11 17 5471