**6.28(梅森素数)如果一个素数可以写成的形式,其中p是某个正整数,那么这个素数就称作梅森素数。编写程序,找出p31的所有梅森素数,然后如下显示输入结果:
**6.28(Mersenne prime) 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 all Mersenne primes with p 31 and displays the output as follows:
下面是参考答案代码:
// https://cn.fankuiba.com
public class Ans6_28_page203 {
public static void main(String[] args) {
System.out.printf("%-15s%5s%s", "p", "2^p-1", "
--------------------
");
double masonPrime;
for (int p = 2; p <= 31; p++) {
masonPrime = Math.pow(2,p)-1;
if (isPrime(masonPrime))
System.out.printf("%-15d%1.0f
",p,masonPrime);
}
}
public static boolean isPrime(double number) {
boolean isPrime = true;
for (int divisor = 2; divisor <= number / 2; divisor++) {
if (number % divisor == 0) {
isPrime = false;
break;
}
}
return isPrime;
}
}
适用Java语言程序设计与数据结构(基础篇)(原书第11版)Java语言程序设计(基础篇)(原书第10/11版)更多内容