Java Method definition calculate Mersenne prime numbers

Question

A prime number is called a Mersenne prime if it can be written in the form 2p - 1 for some positive integer p.

We would like to write a program that finds all Mersenne primes with p <= 31 and displays the output as follows:

p             2^p ?1
-----------------------
2             3
3             7
5             31

public class Main {
  public static void main(String[] args) {
    System.out.println("\np           2^p-1");

    for (int p = 2; p <= 31; p++) {
      if (isPrime(p)) {
        System.out.printf("%-13d", p);
        System.out.println(mersennePrime(p));
      }//from   w w w  .j  a v  a2  s.c  om
    }
  }

  //your code here
}




public class Main {
  public static void main(String[] args) {
    System.out.println("\np           2^p-1");

    for (int p = 2; p <= 31; p++) {
      if (isPrime(p)) {
        System.out.printf("%-13d", p);
        System.out.println(mersennePrime(p));
      }
    }
  }

  public static boolean isPrime(long n) {
    if (n < 2)
      return false;
    for (int i = 2; i <= n / 2; i++) {
      if (n % i == 0)
        return false;
    }
    return true;
  }

  public static int mersennePrime(int num) {
    return (int) Math.pow(2, num) - 1;
  }
}



PreviousNext

Related