Search code examples
javapalindrome

Prime palindrome program goes to infinite loop


public class Lab5{
    public static void main(String[] args){

    Scanner input = new Scanner(System.in);

    System.out.print("Please enter N: ");
    int n = input.nextInt();

    System.out.println("The palindrome prime numbers less than " + n + " are: ");

       for (int x=2; x<n; x++){
          if(isPrime(x) && isPalindrome(x)){
          System.out.print(x+", ");
          }
       }
    }
    public static boolean isPrime(int x){

        for (int i=2; i<x; i++){
            if (x%i ==0)        
            return false;
        }return true;
    }
    public static int reverse(int x){

        int ans=0;
        while (x  != 0){
            ans = ans*10 + x%10;
            x=x/10;
        }return ans;
    }
    public static boolean isPalindrome(int x){

        if (x%reverse(x)  ==0)
            return true;
        else return false;
    }
}

Whenever I enter huge numbers as N i.e 1,000,000 my program goes to an infinite loop. I need help fixing it before the deadline in 10 hours. Any help would be highly appreciated.


Solution

  • It does not go in an infinite loop, just becomes slower and slower.

    For mor feedback, you could make it even a bit slower, using System.out.flush(). This causes the internally buffered line to be shown.

          System.out.print(x+", ");
          System.out.flush();
    

    Now, isPalindrome to my understandings should be just:

    return x == reversed(x);
    

    Concerning speed:

         if(isPrime(x) && isPalindrome(x)){
    

    should be

         if (isPalindrome(x) && isPrime(x)) {
    

    The reason: isPalindrome will rapidly become much faster then isPrime. And && does not evaluate the right hand side when the left hand side is false. And there are even less palindromes than primes.

    Small things:

            x=x/10;
    

    can be written

            x /= 10;
    

    And maybe

        int sqr = (int)Math.sqrt(x);
        if (2 <= sqr) {
            if (x % 2 == 0)        
                return false;
        }
        for (int i = 3; i <= sqr; i += 2) {
            if (x % i == 0)        
                return false;
        }
        return true;