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.
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:
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:
2 3 7 43 13 53 5 6221671 38709183810571 139 2801 11 17 5471
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.