Chankey Pathak
Chankey Pathak

Reputation: 21676

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 correct or are there any problems?

Let me know some other methods to solve this problem. Thank you.

Upvotes: 1

Views: 3299

Answers (3)

Sujith Surendranathan
Sujith Surendranathan

Reputation: 2579

  1. 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)
  2. If 1 is true, then check if it is a palindrome.
  3. If 2 is true, then check if it is prime.

Upvotes: 0

asela38
asela38

Reputation: 4654

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

Upvotes: 0

JOTN
JOTN

Reputation: 6317

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.

Upvotes: 2

Related Questions