Write a program to print all palindromic prime between 2 given elements
I know what a palindromic prime number is. I just want to know how should I make a program for this in Java?
What I am thinking is that I will make two functions -
1) a function which takes the number as argument and checks whether the number is prime or not?
2) a function which takes the number as argument and checks whether it is palindrome or not?
then apply the AND (&&) operator which returns TRUE only if both conditions are true and then print that number on output.
Is this approach corr开发者_C百科ect or are there any problems?
Let me know some other methods to solve this problem. Thank you.
That's a reasonable start but is performance part of the assignment? That's where it would get interesting. You can design a series of tests that can reject possibilities and then order them from the fastest to the slowest. For example just a quick least significant bit check will eliminate all even numbers.
Palindrom is property of a word(String) where reverse of the word is indentical to original eg. "Able was I ere I saw Elba" This is one way you can do this. here I use apache commons lang StringUtil to reverse the number
@org.junit.Test
public void test16() throws Exception {
BigInteger from = new BigInteger("1");
BigInteger to = new BigInteger("100000");
BigInteger palindromicPrime = from;
while((palindromicPrime = palindromicPrime.nextProbablePrime()).compareTo(to) < 0){
if(palindromicPrime.toString().equals(StringUtils.reverse(palindromicPrime.toString()))){
System.out.println(palindromicPrime);
}
}
}
Output :
2
3
5
7
11
101
131
151
181
191
313
353
373
383
727
757
787
797
919
929
10301
10501
10601
11311
11411
12421
- If number is greater than 10, check if the number ends in 1,3,7 or 9 (In other words, increment according the 1,3,7,9 sequence). (Note: 2 and 5 are prime numbers, so do not eliminate all even numbers, or all numbers ending in 5)
- If 1 is true, then check if it is a palindrome.
- If 2 is true, then check if it is prime.
精彩评论