Mersenne Prime | Program to generate mersenne primes ; Generate all prime numbers less than n . ; Initialize all entries of boolean array as true . A value in prime [ i ] will finally be false if i is Not a prime , else true bool prime [ n + 1 ] ; ; If prime [ p ] is not changed , then it is a prime ; Update all multiples of p ; Function to generate mersenne primes lessthan or equal to n ; Create a boolean array " prime [ 0 . . n ] " ; Generating primes using Sieve ; Generate all numbers of the form 2 ^ k - 1 and smaller than or equal to n . ; Checking whether number is prime and is one less then the power of 2 ; Driven program
import java . io . * ; class GFG { static void SieveOfEratosthenes ( int n , boolean prime [ ] ) { for ( int i = 0 ; i <= n ; i ++ ) prime [ i ] = true ; for ( int p = 2 ; p * p <= n ; p ++ ) { if ( prime [ p ] == true ) { for ( int i = p * 2 ; i <= n ; i += p ) prime [ i ] = false ; } } } static void mersennePrimes ( int n ) { boolean prime [ ] = new boolean [ n + 1 ] ; SieveOfEratosthenes ( n , prime ) ; for ( int k = 2 ; ( ( 1 << k ) - 1 ) <= n ; k ++ ) { long num = ( 1 << k ) - 1 ; if ( prime [ ( int ) ( num ) ] ) System . out . print ( num + " ▁ " ) ; } } public static void main ( String args [ ] ) { int n = 31 ; System . out . println ( " Mersenne ▁ prime " + " numbers ▁ smaller ▁ than " + " or ▁ equal ▁ to ▁ " + n ) ; mersennePrimes ( n ) ; } }