VOOZH about

URL: https://www.geeksforgeeks.org/dsa/mersenne-prime/

⇱ Program to Find All Mersenne Primes till N - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Program to Find All Mersenne Primes till N

Last Updated : 10 Oct, 2024

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.

Output:

Mersenne prime numbers smaller than or equal to 31
3 7 31

Time Complexity : O (n*log(logn))

Space Complexity : O(N)


References:
https://en.wikipedia.org/wiki/Mersenne_prime

Comment
Article Tags:
Article Tags: