QuestionAsk Questions?

how to find prime numbers in a given range which are palindromes??

View Answers

December 21, 2010 at 5:12 PM

Hi Friend,

Try the following code:

import java.util.*; public class PrimeAndPalindrome { static final int MAXNUMBER=200; 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==0 || 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=(int) Math.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); } } }

Thanks

December 23, 2010 at 10:49 AM

thnks buddy..but can u clearify what that ArrayList exactly doing?

Related Tutorials/Questions & Answers: