我試圖解決一個問題,要求找到最小的主要回文,它在給定數字後出現,這意味着如果輸入是24,輸出將是101,因爲它是最小數字之後24既是素數也是迴文。java程序中的StackOverFlowError
現在我的代碼完美適用於較小的值,但是當我插入類似於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);
}
}
}
}
謝謝我明白你在說什麼。我不禁要問另一個問題。這個堆棧的大小是依賴於機器還是依賴於語言,還是兩者兼得或無? – tofu
它依賴於機器和語言。看到這篇文章中的默認堆棧大小在不同jvms的java中http://stackoverflow.com/questions/6020619/where-to-find-default-xss-value-for-sun-oracle-jvm – marcelv3612