Find Numbers which are palindrome and prime


 

Find Numbers which are palindrome and prime

In this section, you will learn how to find the numbers from 1 to 500 which are palindrome and prime.

In this section, you will learn how to find the numbers from 1 to 500 which are palindrome and prime.

Find Numbers which are palindrome and prime

In this section, you will learn how to find the numbers from 1 to 500 which are palindrome and prime. To compute this, we have created two methods isPalindrome() of ArrayList type and isPrime() of boolean type. Now the list contains all the numbers which are palindrome. The Iterator class iterates the ArrayList and check whether number is prime or not. If it is prime, the number will get displayed.

Here is the code:

    import java.util.*;

    public class PrimeAndPalindrome {
       static final int MAXNUMBER=500;
       private int number;
       private ArrayList<Integer> list = new ArrayList<Integer>();
       public PrimeAndPalindrome(int maxNum){
       number=maxNum;
       }
     ArrayList<Integer> isPalindrome(){
          for (int i=10; i<=number; i++){
             Integer in=new Integer(i);
             String number=in.toString();
             int index1=0;
             int index2=number.length()-1;
             char x=number.charAt(index1);
             char y=number.charAt(index2);
             while (index2-index1>=0){
             if(x!=y)
             break;
             if (index2-index1==|| index2-index1==1)
             list.add(i);
             index1++;
             index2--;
             x=number.charAt(index1);
             y=number.charAt(index2);
             }
          }
          return list;
       }
       static boolean isPrime(int number){
          boolean isPrime=false;
          int i=(intMath.ceil(Math.sqrt(number));
          while (i>1){
             if ((number!=i&& (number%i==0)){
                isPrime=false;
                break;
             }
             else if (!isPrime)
             isPrime=true;
             --i;
          }
          return isPrime;
       }
       public static void main(String[] args) {
          ArrayList<Integer> palindromes=new ArrayList<Integer>();
          PrimeAndPalindrome pp=new PrimeAndPalindrome(MAXNUMBER);
          palindromes=pp.isPalindrome();
          Iterator<Integer> iter=palindromes.iterator();
          while (iter.hasNext()){
             int current=iter.next();
             if (isPrime(current))
                System.out.println(current);
          }
       }
    }

Output:

11
101
131
151
181
191
313
353
373
383

Ads