第六章第二十九题(双素数)(Twin primes) - 编程练习题答案

2022-03-29 13:12:10 浏览数 (1)

**6.29(双素数)双素数是指一对差值为2的素数。例如:3和5就是一对双素数,5和7是一对双素数,而11和13也是一对双素数。编写程序,找出小于1000的所有双素数。如下所示显示结果:

(3,5)

(5,7)

**6.29(Twin primes)(Twin primes) Twin primes are a pair of prime numbers that differ by 2. For example, 3 and 5 are twin primes, 5 and 7 are twin primes, and 11 and 13 are twin primes. Write a program to find all twin primes less than 1,200. Display the output as follows:

(3,5)

(5,7)

下面是参考答案代码:

代码语言:javascript复制
// https://cn.fankuiba.com
public class Ans6_29_page203 {
    public static void main(String[] args) {
        for (int p = 3; p 2 < 1000; p  ) {
            if (isPrime(p) && isPrime(p 2))
                System.out.println("(" p "," (p 2) ")");
        }
    }

    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 人点赞