Search code examples
javaprimespalindrome

How would I print out a pair of emirp numbers with user input for the number of pairs?


I have a program where I need to print out emirp pairs when the user inputs how many pairs they would like to display. Within the program I have the main function and three other functions.

//returns true if num is prime
public static boolean isPrime(int num)

//returns the reverse of number
public static int reversal(int number)

//returns true if number is a palindrome
public static boolean isPalindrome(int number)

The main function accepts user input and then will pass the user value to another function that will print the pairs. I'm lost on this part as I know how to print the pairs within a range and including duplicates as shown below but not with a given number of pairs. Any help would be appreciated!

public static void printPairs(int pairs) {
    
    for (int i = 0; i < 100; i++) {
        int rev = reversal(i);
        if (isPrime(i) == true && isPrime(rev) == true && isPalindrome(i) == false) {
            System.out.print("(" + i + "," + rev + ") ");
        }
    }
}

Output: (13,31) (17,71) (31,13) (37,73) (71,17) (73,37) (79,97) (97,79) 

Solution

  • Like this?

    public static void printPairs(int pairs) {
        
        for (int i = 0; i < 100; i++) {
            int rev = reversal(i);
            if (isPrime(i) == true && isPrime(rev) == true && isPalindrome(i) == false) {
                System.out.print("(" + i + "," + rev + ") ");
                if ((pairs--) < 0) {
                    return;
                }
            }
        }
    }
    

    That is, just exit when you get the number of pairs?

    Two other suggestions: don't limit yourself to 100, and eliminate duplicates by only considering cases where the reversal number is higher than the current number. (If it is lower, then it would already have been printed).

    public static void printPairs(int pairs) {
        int i=10;
        while (pairs > 0) {
            i++;
            int rev = reversal(i);
            if (rev<i) {
                continue;
            }
            if (isPrime(i) == true && isPrime(rev) == true && isPalindrome(i) == false) {
                System.out.print("(" + i + "," + rev + ") ");
                pairs--;
            }
        }
    }
    

    Teachers generally don't like continue statements, so you can fold the condition into the main condition statement. P.S. 10 is the first non-palindrome number.