【发布时间】:2014-11-16 05:29:30
【问题描述】:
我正在尝试解决一个问题,该问题要求找到最小的素数回文数,它出现在给定数字之后,这意味着如果输入是 24,则输出将是 101,因为它是 24 之后的最小数字,两者都是素数和回文。
现在我的代码非常适合小值,但是当我插入类似 543212 作为输入的那一刻,我最终在第 20 行出现 StackOverFlowError,然后在第 24 行出现多个 StackOverFlowErrors 实例。这是我的代码:
package nisarg;
import java.util.Scanner;
public class Chef_prime_palindromes {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
long num = input.nextLong();
isPalindrome(num + 1);
}
public static boolean isPrime(long num) {
long i;
for (i = 2; i < num; i++) {
if (num % i == 0) {
return false;
}
}
return true;
}
public static void isPalindrome(long num) {
String word = Long.toString(num);
int i;
for (i = 0; i < word.length() / 2; i++) {
if (word.charAt(i) != word.charAt(word.length() - i - 1)) {
isPalindrome(num + 1);
}
}
if (i == word.length() / 2) {
if (isPrime(num)) {
System.out.println(num);
System.exit(0);
} else {
isPalindrome(num + 1);
}
}
}
}
【问题讨论】:
标签: java recursion stack-overflow