第六章第二十九题(双素数)(Twin primes)
**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) …参考代码:
package chapter06
;
public class Code_29 {
public static void main(String
[] args
) {
for(int i
= 3;i
+ 2 < 1000;i
++)
if(isPrime(i
) && isPrime(i
+2))
System
.out
.printf("(%d, %d)\n", i
, i
+2);
}
public static boolean isPrime(int number
) {
for(int i
= 2;i
<= Math
.sqrt(number
);i
++)
if(number
% i
== 0)
return false;
return true;
}
}
结果显示:
(3, 5)
(5, 7)
(11, 13)
(17, 19)
(29, 31)
(41, 43)
(59, 61)
(71, 73)
(101, 103)
(107, 109)
(137, 139)
(149, 151)
(179, 181)
(191, 193)
(197, 199)
(227, 229)
(239, 241)
(269, 271)
(281, 283)
(311, 313)
(347, 349)
(419, 421)
(431, 433)
(461, 463)
(521, 523)
(569, 571)
(599, 601)
(617, 619)
(641, 643)
(659, 661)
(809, 811)
(821, 823)
(827, 829)
(857, 859)
(881, 883)
Process finished with exit code
0