(Palindromic prime) 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 727 757 787 797 919 929
…
PalindromicPrime.java
/**
* Palindromic prime number.
*/
public class PalindromicPrime {
//** main method */
public static void main(String[] args) {
// Declare and initialize variables
int count=1,number=2;
String result="";
while(count<=100){
if(Prime(number) && Palindromic(number)){ // is the number palindromic prime?
if(count%10==0){
result += " "+number+"\n";
}else{
result += " "+number;
}
count++;
}
number++;
}
System.out.print(result); // Print the first palindromic prime numbers.
} // End of main method.
/** Prime method */
public static boolean Prime(int num){
// Prime calculation of the first way. This way faster than other ways.
int count = 0;
for(int divisor=2;divisor<=num/2;divisor++){
if(num%divisor==0){
return false; // if the number is not prime return false.
}
}
return true; // if the number is prime return true.
/** Prime calculation of the second way.
int count = 0;
for(int divisor=2;divisor<=num/2;divisor++){
if(num%divisor==0){
count++;
}
}
if(count==0){
return true; // if the number is prime return true.
}
return false; // if the number is not prime return false.
*/
/** Prime calculation of the third way.
int count = 0;
for(int divisor=1;divisor<=num/2;divisor++){
if(num%divisor==0){
count++;
}
}
if(count==1){
return true; // if the number is prime return true.
}
return false; // if the number is not prime return false.
*/
/** Prime calculation of the fourth way.
int count = 0;
for(int divisor=1;divisor<=num;divisor++){
if(num%divisor==0){
count++;
}
}
if(count==2){
return true; // if the number is prime return true.
}
return false; // if the number is not prime return false.
*/
} // End of Prime method.
/** Palindromic method */
public static boolean Palindromic(int num){
// Declare and initialize variables
int result = 0;
int number = num;
// The number reversing.
while(num!=0){
int lastDigit= num%10;
result = result*10+lastDigit;
num /=10;
} // End of while num!=0
if(number==result){
return true; // if the number is palindromic return true.
}
return false; // if the number is not palindromic return false.
} // End of Palindromic method.
} // End of class.
Yorum Yok:
Yorum Yap:
Yorum yapabilmek için giriş yapmalısınız.



