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
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