Euclidâ €“ Mullin Sequence | Java implementation of the approach ; Function to return the smallest prime factor of n ; Initialize i = 2 ; While i <= sqrt ( n ) ; If n is divisible by i ; Increment i ; Function to print the first n terms of the required sequence ; To store the product of the previous terms ; Traverse the prime numbers ; Current term will be smallest prime factor of ( 1 + product of all previous terms ) ; Print the current term ; Update the product ; Driver code ; Find the first 14 terms of the sequence
import java . math . BigInteger ; class GFG { static BigInteger smallestPrimeFactor ( BigInteger n ) { BigInteger i = BigInteger . valueOf ( 2 ) ; while ( ( i . multiply ( i ) ) . compareTo ( n ) <= 0 ) { if ( n . mod ( i ) . compareTo ( BigInteger . ZERO ) == 0 ) return i ; i = i . add ( BigInteger . ONE ) ; } return n ; } static void solve ( BigInteger n ) { BigInteger product = BigInteger . ONE ; BigInteger i = BigInteger . ZERO ; while ( i . compareTo ( n ) < 0 ) { BigInteger num = smallestPrimeFactor ( product . add ( BigInteger . ONE ) ) ; System . out . print ( num + " ▁ " ) ; product = product . multiply ( num ) ; i = i . add ( BigInteger . ONE ) ; } } public static void main ( String [ ] args ) { BigInteger b = BigInteger . valueOf ( 14 ) ; solve ( b ) ; } }