我正在尝试做一个程序来显示前50个质数回文,每行有10个数字。这是我到目前为止所拥有的代码,但是当运行时什么都没有发生。我已经寻找过类似的解决方案,但似乎找不到错误所在。任何帮助都将不胜感激。
import java.lang.Math;
public class PalindromicPrime {
public static void main(String[] args) {
int counter = 1;
int start = 2;
isPalindrome(start);
isPrime(start);
while (counter <= 50) {
if (isPrime(start) && isPalindrome(start)) {
System.out.print(start + " ");
if (counter % 10 == 0) {
System.out.println();
counter++;
}
start++;
}
}
}
public static boolean isPalindrome(int x) {
int reverse = 0;
while(x > 0) {
reverse = reverse * 10 + x % 10;
x = x / 10;
}
if (reverse == x) {
return true;
}
else {
return false;
}
}
public static boolean isPrime(int x) {
if (x % 2 == 0 && x != 2) {
return false;
}
int sqr = (int)Math.sqrt(x);
for (int i = 3; i <= sqr; i += 2) {
if(x % i == 0) {
return false;
}
}
return true;
}
}
发布于 2019-02-28 22:27:35
你的代码是一个无限循环。这是因为您在if语句中增加了start
,所以只有当start是质数和回文数字时才会递增。如果start
不是回文或质数,它将不会进入条件,因此counter
将Nevers递增并达到50
https://stackoverflow.com/questions/54934978
复制