第六章第二十八题(梅森素数)(Mersenne prime) - 编程练习题答案

2022-03-29 13:11:59 浏览数 (1)

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

下面是参考答案代码:

代码语言:javascript复制
// 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", "n--------------------n");

        double masonPrime;
        for (int p = 2; p <= 31; p  ) {
            masonPrime = Math.pow(2,p)-1;
            if (isPrime(masonPrime))
                System.out.printf("%-15d%1.0fn",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;
    }
}

0 人点赞