Euclid–Mullin Sequence

Given an integer N, the task is to print the first N elements of the Euclid-Mullin Sequence.
The Euclid-Mullin sequence is a sequence of prime numbers where each element is the least prime factor of one plus the product of all earlier elements.
The sequence is named after the ancient Greek mathematician Euclid.

Examples:

Input: N = 14
Output: 2 3 7 43 13 53 5 6221671 38709183810571 139 2801 11 17 5471



Approach: The Euclid–Mullin sequence is a sequence of prime numbers where the nth number of sequence is:
a(n) = Least prime factor of ( 1 + \sum_{x=1}^{n-1} a(x)) \\
So, we will run a loop from 1 to N and take a variable product which is initially to 1 and will contain the product of all previous elements. We will then find the smallest prime factor of (1 + product) in O(sqrt(n)) time and print the number. Note that the code fails to print numbers after the 14th element as the product becomes too large and finding its smallest prime factor takes a lot of time.

Below is the implementation of the above approach:

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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);
    }
}

chevron_right


Output:

2 3 7 43 13 53 5 6221671 38709183810571 139 2801 11 17 5471


My Personal Notes arrow_drop_up

Recommended Posts:



    Article Tags :
    Practice Tags :


    Be the First to upvote.


    Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.