Home Tutorial Java Core Find Numbers which are palindrome and prime

 
 

Share on Google+Share on Google+
Find Numbers which are palindrome and prime
Posted on: October 23, 2009 at 12:00 AM
Advertisement
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
Advertisement

Related Tags for Find Numbers which are palindrome and prime:


Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.

Posted on: October 23, 2009

Recommend the tutorial

Advertisements Advertisements
 

 

 

DMCA.com