**6.28 (Messen prime number) If a prime number can be written in the form of 2^p-1, where p is a positive integer, then this prime number is called a Mersenne prime number. Write a program to find all Mersenne prime numbers with p<=31, and then display the input results as follows: p 2^p-1 2 3 3 7 5 31 … **6.28(Mersenne prime) A prime number is called a Mersenne prime if it can be written in the form 2^p-1 for some positive integer p. 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 …
Reference Code:
package chapter06;publicclassCode_28{
publicstaticvoidmain(String[] args){
printTableHead();for(int i =2;i <=31;i++)if(isPrime((long)(Math.pow(2, i)-1)))
System.out.printf("%d\t\t%d\n", i,(long)(Math.pow(2, i)-1));}publicstaticbooleanisPrime(long number){
for(int i =2; i <= Math.sqrt(number); i++)if(number % i ==0)returnfalse;returntrue;}publicstaticvoidprintTableHead(){
System.out.println("p\t\t2^p-1");for(int i =1;i <=24;i++)
System.out.print("-");
System.out.print("\n");}}
The results show that:
p 2^p-1------------------------233753171271381911713107119524287312147483647
Process finished with exit code 0