Mersenne Prime - GeeksforGeeks

26 Mar, 2021
Mersenne Prime is a prime number that is one less than a power of two. In other words, any prime is Mersenne Prime if it is of the form 2k-1 where k is an integer greater than or equal to 2. First few Mersenne Primes are 3, 7, 31 and 127.The task is print all Mersenne Primes smaller than an input positive integer n.Examples:  
Input: 10
Output: 3 7
3 and 7 are prime numbers smaller than or
equal to 10 and are of the form 2k-1

Input: 100
Output: 3 7 31 
 
The idea is to generate all the primes less than or equal to the given number n using Sieve of Eratosthenes. Once we have generated all such primes, we iterate through all numbers of the form 2k-1 and check if they are primes or not.Below is the implementation of the idea. 
C++
Java
Python3
C#
PHP
Javascript
// Program to generate mersenne primes#include<bits/stdc++.h>using namespace std; // Generate all prime numbers less than n.void SieveOfEratosthenes(int n, bool prime[]){    // 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];    for (int i=0; i<=n; i++)        prime[i] = true;     for (int p=2; p*p<=n; p++)    {        // If prime[p] is not changed, then it        // is a prime        if (prime[p] == true)        {            // Update all multiples of p            for (int i=p*2; i<=n; i += p)                prime[i] = false;        }    }} // Function to generate mersenne primes less// than or equal to nvoid mersennePrimes(int n){    // Create a boolean array "prime[0..n]"    bool prime[n+1];     // Generating primes using Sieve    SieveOfEratosthenes(n,prime);     // Generate all numbers of the form 2^k - 1    // and smaller than or equal to n.    for (int k=2; ((1<<k)-1) <= n; k++)    {        long long num = (1<<k) - 1;         // Checking whether number is prime and is        // one less then the power of 2        if (prime[num])            cout << num << " ";    }} // Driven programint main(){    int n = 31;    cout << "Mersenne prime numbers smaller "         << "than or equal to " << n << endl;    mersennePrimes(n);    return 0;}
// Program to generate// mersenne primesimport java.io.*; class GFG {         // Generate all prime numbers    // less than n.    static void SieveOfEratosthenes(int n,                          boolean prime[])    {        // 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];        for (int i = 0; i <= n; i++)            prime[i] = true;             for (int p = 2; p * p <= n; p++)        {            // If prime[p] is not changed            // , then it is a prime            if (prime[p] == true)            {                // Update all multiples of p                for (int i = p * 2; i <= n; i += p)                    prime[i] = false;            }        }    }         // Function to generate mersenne    // primes lessthan or equal to n    static void mersennePrimes(int n)    {        // Create a boolean array        // "prime[0..n]"        boolean prime[]=new boolean[n + 1];             // Generating primes        // using Sieve        SieveOfEratosthenes(n, prime);             // Generate all numbers of        // the form 2^k - 1 and        // smaller than or equal to n.        for (int k = 2; (( 1 << k) - 1) <= n; k++)        {            long num = ( 1 << k) - 1;                 // Checking whether number is            // prime and is one less then            // the power of 2            if (prime[(int)(num)])                System.out.print(num + " ");        }    }         // Driven program    public static void main(String args[])    {        int n = 31;        System.out.println("Mersenne prime"+                     "numbers smaller than"+                          "or equal to "+n);                 mersennePrimes(n);    }} // This code is contributed by Nikita Tiwari.
# Program to generate mersenne primes # Generate all prime numbers# less than n.def SieveOfEratosthenes(n, prime):     # 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]    for i in range(0, n + 1) :        prime[i] = True     p = 2    while(p * p <= n):             # If prime[p] is not changed,        # then it is a prime        if (prime[p] == True) :                     # Update all multiples of p            for i in range(p * 2, n + 1, p):                prime[i] = False                         p += 1         # Function to generate mersenne# primes less than or equal to ndef mersennePrimes(n) :     # Create a boolean array    # "prime[0..n]"    prime = [0] * (n + 1)     # Generating primes using Sieve    SieveOfEratosthenes(n, prime)     # Generate all numbers of the    # form 2^k - 1 and smaller    # than or equal to n.    k = 2    while(((1 << k) - 1) <= n ):             num = (1 << k) - 1         # Checking whether number        # is prime and is one        # less then the power of 2        if (prime[num]) :            print(num, end = " " )                     k += 1     # Driver Coden = 31print("Mersenne prime numbers smaller",              "than or equal to " , n )mersennePrimes(n) # This code is contributed# by Smitha
// C# Program to generate mersenne primesusing System; class GFG {         // Generate all prime numbers less than n.    static void SieveOfEratosthenes(int n,                                bool []prime)    {                 // 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];        for (int i = 0; i <= n; i++)            prime[i] = true;             for (int p = 2; p * p <= n; p++)        {                         // If prime[p] is not changed,            // then it is a prime            if (prime[p] == true)            {                                 // Update all multiples of p                for (int i = p * 2; i <= n; i += p)                    prime[i] = false;            }        }    }         // Function to generate mersenne    // primes lessthan or equal to n    static void mersennePrimes(int n)    {                 // Create a boolean array        // "prime[0..n]"        bool []prime = new bool[n + 1];             // Generating primes        // using Sieve        SieveOfEratosthenes(n, prime);             // Generate all numbers of        // the form 2^k - 1 and        // smaller than or equal to n.        for (int k = 2; (( 1 << k) - 1) <= n; k++)        {            long num = ( 1 << k) - 1;                 // Checking whether number is            // prime and is one less then            // the power of 2            if (prime[(int)(num)])                Console.Write(num + " ");        }    }         // Driven program    public static void Main()    {        int n = 31;                 Console.WriteLine("Mersenne prime numbers"               + " smaller than or equal to " + n);                 mersennePrimes(n);    }} // This code is contributed by nitin mittal.
<?php// Program to generate mersenne primes // Generate all prime numbers less than n.function SieveOf($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    $prime = array($n + 1);    for ($i = 0; $i <= $n; $i++)        $prime[$i] = true;     for ($p = 2; $p * $p <= $n; $p++)    {        // If prime[p] is not changed,        // then it is a prime        if ($prime[$p] == true)        {            // Update all multiples of p            for ($i = $p * 2; $i <= $n; $i += $p)                $prime[$i] = false;        }    }    return $prime;} // Function to generate mersenne// primes less than or equal to nfunction mersennePrimes($n){    // Create a boolean array "prime[0..n]"    // bool prime[n+1];     // Generating primes using Sieve    $prime = SieveOf($n);     // Generate all numbers of the    // form 2^k - 1 and smaller    // than or equal to n.    for ($k = 2; ((1 << $k) - 1) <= $n; $k++)    {        $num = (1 << $k) - 1;         // Checking whether number is prime        // and is one less then the power of 2        if ($prime[$num])            echo $num . " ";     }} // Driver Code$n = 31;echo "Mersenne prime numbers smaller " .     "than or equal to $n " .      mersennePrimes($n); // This code is contributed by mits?>
<script> // JavaScript to generate// mersenne primes     // Generate all prime numbers    // less than n.    function SieveOfEratosthenes( n,                          prime)    {        // 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];        for (let i = 0; i <= n; i++)            prime[i] = true;               for (let p = 2; p * p <= n; p++)        {            // If prime[p] is not changed            // , then it is a prime            if (prime[p] == true)            {                // Update all multiples of p                for (let i = p * 2; i <= n; i += p)                    prime[i] = false;            }        }    }           // Function to generate mersenne    // primes lessthan or equal to n    function mersennePrimes(n)    {        // Create a boolean array        // "prime[0..n]"        let prime=[];               // Generating primes        // using Sieve        SieveOfEratosthenes(n, prime);               // Generate all numbers of        // the form 2^k - 1 and        // smaller than or equal to n.        for (let k = 2; (( 1 << k) - 1) <= n; k++)        {            let num = ( 1 << k) - 1;                   // Checking whether number is            // prime and is one less then            // the power of 2            if (prime[(num)])               document.write(num + " ");        }    } // Driver Code        let n = 31;        document.write("Mersenne prime"+                     "numbers smaller than"+                          "or equal to "+n + "<br/>");                   mersennePrimes(n); // This code is contributed by code_hunt.</script>
Output:  
Mersenne prime numbers smaller than or equal to 31
3 7 31 
References: https://en.wikipedia.org/wiki/Mersenne_primeThis article is contributed by Rahul Agrawal. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. 
nitin mittal
Smitha Dinesh Semwal
Mithun Kumar
code_hunt
Prime Number
sieve
Mathematical
Mathematical
Prime Number
sieve
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Merge two sorted arrays
Modulo Operator (%) in C/C++ with Examples
Prime Numbers
Print all possible combinations of r elements in a given array of size n
The Knight's tour problem | Backtracking-1
Operators in C / C++
Program for factorial of a number
Find minimum number of coins that make a given value
Program to find sum of elements in a given array
Minimum number of jumps to reach end