**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)
…
下面是参考答案代码:
// 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;
}
}
适用Java语言程序设计与数据结构(基础篇)(原书第11版)Java语言程序设计(基础篇)(原书第10/11版)更多内容
网友评论