Finding Mersenne Prime Numbers in Java

Problem:

A prime number is called a Mersenne prime if it can be written in the form for some positive integer p. Write a program that finds Mersenne primes numbers as seen in the output.


Output:

p 2^p-1
2 3
3 7
5 31
7 127
13 8191
17 131071
19 524287
31 2147483647


Solution:

public class MersennePrime
{
  public static boolean isPrime(int N)
  {
    for (int i = 2;i<=Math.sqrt(N);i++)
    {
      if (N%i == 0)
        return false;
    }
    return true;
  }
  
  public static void main (String[] args)
  {
    System.out.println("p" +"\t"+ "2^p-1");    
    for (int i =2;i<=34;i++)
    {
      if (isPrime(i) && isPrime((int) (Math.pow(2, i)-1)))
      {
          System.out.println(i +"\t" + (int) (Math.pow(2, i)-1));
      }
    }
  }
}



No comments :

Post a Comment

Follow Me

If you like our content, feel free to follow me to stay updated.

Subscribe

Enter your email address:

We hate spam as much as you do.

Upload Material

Got an exam, project, tutorial video, exercise, solutions, unsolved problem, question, solution manual? We are open to any coding material. Why not upload?

Upload

Copyright © 2012 - 2014 Java Problems  --  About  --  Attribution  --  Privacy Policy  --  Terms of Use  --  Contact