反素数是指一个非回文素数,将其反转之后也是一个素数(例如:13和31,17和71)。回文素数就是相应位置对称的素数(例如11,101,757)。
Java实现反素数的过程可以分为两个方法,第一个方法判断一个数和它的反数是否都为素数,并且是非回文数,第二方法是判断一个数是否为素数,供第一个方法调用。
具体代码如下:
package itcast_01;
import java.util.Scanner;
public class test02 {
public static void main(String[] args) {
Scanner input=new Scanner(System.in);
System.out.print("Please enter a number for counts: ");
int counts=input.nextInt();
isPrimeCount(counts);
}
public static void isPrimeCount(int num) {
int count=0;
int number=13;
while (count<num) {
String number1=String.valueOf(number);
int len=number1.length();
int number2=0;
for (int j=0;j<len;j++) {
int m=number1.charAt(len-j-1)-'0';// 将字符型数字转化为十进制数字
number2+=m*Math.pow(10, len-j-1);//将m乘以所在位的次方,累加得到number的反数
}
if (isPrime(number)&&isPrime(number2)&&number!=number2) {
count++;
if (count%10==0) {
System.out.printf("%5d\n",number);
}
else
System.out.printf("%5d",number);
}
number++;
}
}
public static boolean isPrime(int n) {
for (int i=2;i<=n/2;i++) {
if (n%i==0)
return false;
}
return true;
}//此方法用来判定素数
}
运行结果:
Please enter a number for counts: 100
13 17 31 37 71 73 79 97 107 113
149 157 167 179 199 311 337 347 359 389
701 709 733 739 743 751 761 769 907 937
941 953 967 971 983 991 1009 1021 1031 1033
1061 1069 1091 1097 1103 1109 1151 1153 1181 1193
1201 1213 1217 1223 1229 1231 1237 1249 1259 1279
1283 1301 1321 1381 1399 1409 1429 1439 1453 1471
1487 1499 1511 1523 1559 1583 1597 1601 1619 1657
1669 1723 1733 1741 1753 1789 1811 1831 1847 1867
1879 1901 1913 1933 1949 1979 3011 3019 3023 3049