我正在尝试制作一个程序,以显示每行10个数字的前50个主要回文。这是我到目前为止的代码,但是当运行时没有任何反应。我看过类似的解决方案,似乎无法找到错误。任何帮助,将不胜感激。
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;
}
}
首先,正如其他人所说,你的isPalindrome()
方法无法正常工作。
我建议你只需将你的int转换成一个字符串,然后检查它是否是回文。我认为这是最简单的方法。也许其他人可以评论这在性能方面是否是一个坏主意。
我将如何做到这一点:
public static boolean isPalin(int x) {
String s = Integer.toString(x);
for(int i = 0; i < s.length()/2; i++) {
if(s.charAt(i) != s.charAt(s.length()-i-1)) {
return false;
}
}
return true;
}
你的while循环也没有正常工作,因为你只是在实际找到素数时才增加开始。每次找到素数时,计数器都应递增。 最重要的是,您应该将while循环的条件基于起始值,而不是换行符的计数器 。 编辑:实际上你应该在while条件下使用counter。我错了。
这是更新的代码:
public static void main(String[] args) {
int counter = 0;
int start = 2;
while (counter < 50) {
if (isPrime(start) && isPalin(start)) {
System.out.print(start + " ");
counter++;
if (counter % 10 == 0) {
System.out.println();
}
}
start++;
}
}
public static boolean isPalin(int x) {
String s = Integer.toString(x);
for(int i = 0; i < s.length()/2; i++) {
if(s.charAt(i) != s.charAt(s.length()-i-1)) {
return false;
}
}
return true;
}
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;
}
这是前50个回文素数的输出:
2 3 5 7 11 101 131 151 181 191
313 353 373 383 727 757 787 797 919 929
10301 10501 10601 11311 11411 12421 12721 12821 13331 13831
13931 14341 14741 15451 15551 16061 16361 16561 16661 17471
17971 18181 18481 19391 19891 19991 30103 30203 30403 30703
start
,所以当你击中你的第一个非素数时你会遇到一个无限循环。把你的start++
放在if语句之外。isPalindrome()
方法被打破了。变量x
被削减以创建reverse
,但是然后您将reverse
与x
的修改版本进行比较而不是其原始值。counter
,所以这将最终印刷500个回文素数,而不是50。额外奖励:如果你存储你找到的每个素数,那么找到素数会更快,然后只检查先前找到的素数的除法。
您的代码是无限循环。这是因为你在if语句中增加start
,所以只有当start是素数和回文数时。如果start
不是回文或素数,它将不会进入条件,因此counter
将讷韦尔incréée达到50