A palindromic prime is a prime number and also palindromic. For example, 131 is
ID: 3676998 • Letter: A
Question
A palindromic prime is a prime number and also palindromic. For example, 131 is a prime and also a palindromic prime, as are 313 and 757. Write a program that displays the first 100 palindromic prime numbers. Display 10 numbers per line, separated by exactly one space, as follows:
2 3 5 7 11 101 131 151 181 191 313 353 373 383 727 757 787 797 919 929 ...
The code does not print any numbers and I do not know why
import java.util.*;
public class PhoneKeypad
{
public static void main (String[] args)
{
Scanner input = new Scanner(System.in);
System.out.println("The first 100 palindrome numbers are ");
int count = 0;
int total = 0;
for (int a = 0; total <=100; a++)
{
while (count != 10)
{
if (prime(a)==true && palindrome(a)==true)
{
System.out.print(a+" ");
count++;
total++;
}
}
if (count == 10)
count = 0;
System.out.println();
}
}
public static boolean prime(int x)
{
boolean prime = false;
if (x%2 != 0)
if (x%3 != 0)
if (x%4 != 0)
if (x%5 != 0)
if (x%6 != 0)
if (x%7 != 0)
if (x%8 != 0)
if (x%9 != 0)
prime = true;
return prime;
}
public static boolean palindrome(int b)
{
boolean palindrome = false;
int result = 0;
while (b != 0)
{
int lastDigit = b%10;
result = result*10+lastDigit;
b = b/10;
}
if (result == b)
palindrome = true;
return palindrome;
}
}
Explanation / Answer
import java.util.*;
import java.lang.*;
import java.io.*;
public class ProgrammingExercise{
public static void main(String[] args) {
final int NUMBER_OF_PALINPRIME = 100;
int numberPrinted = 0, testedNumber = 2;
while (numberPrinted < NUMBER_OF_PALINPRIME) {
if (isPrime(testedNumber) && isPalindrome(testedNumber)) {
numberPrinted++;
System.out.print(testedNumber + " ");
if (numberPrinted % 10 == 0) {
System.out.println();
}
}
testedNumber++;
}
}
/** Check whether number is prime */
public static boolean isPrime(int number) {
for (int divisor = 2; divisor <= number / 2; divisor++) {
if (number % divisor == 0) { // If true, number is not prime
return false; // number is not a prime
}
}
return true; // number is prime
}
public static int reverse(int number) {
int reverse = 0;
int digit;
do {
digit = number % 10;
reverse = reverse * 10 + digit;
number /= 10;
} while (number != 0);
return reverse;
}
public static boolean isPalindrome(int number) {
return (number == reverse(number));
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.