Skip to content

Commit 22e7f7f

Browse files
authored
Update PalindromicPrime.java
Method prime(num) uses only odd numbers from 3 to square root of num as divisors. In method functioning(y) we iterate over odd numbers as all even numbers (except of 2) are not prime. In method functioning(y) we check at first if the number is palindrome and then if it's prime, so we don't have to call the heavy prime() method for every number. The speed of searching palindromic primes is significantly increased.
1 parent 46a384b commit 22e7f7f

File tree

1 file changed

+21
-18
lines changed

1 file changed

+21
-18
lines changed

Misc/PalindromicPrime.java

+21-18
Original file line numberDiff line numberDiff line change
@@ -1,41 +1,44 @@
11
import java.util.Scanner;
2+
23
public class PalindromePrime {
34

45
public static void main(String[] args) { // Main funtion
56
Scanner in = new Scanner(System.in);
67
System.out.println("Enter the quantity of First Palindromic Primes you want");
7-
int n = in.nextInt(); // Input of how mant first pallindromic prime we want
8-
funtioning(n); // calling funtion - functioning
8+
int n = in.nextInt(); // Input of how many first pallindromic prime we want
9+
functioning(n); // calling function - functioning
910
}
1011

1112
public static boolean prime(int num) { // checking if number is prime or not
12-
for (int divisor = 2; divisor <= num / 2; divisor++) {
13+
for (int divisor = 3; divisor <= Math.sqrt(num); divisor += 2) {
1314
if (num % divisor == 0) {
1415
return false; // false if not prime
1516
}
1617
}
1718
return true; // True if prime
1819
}
1920

20-
public static int reverse(int n){ // Returns the reverse of the number
21+
public static int reverse(int n) { // Returns the reverse of the number
2122
int reverse = 0;
22-
while(n!=0){
23-
reverse = reverse * 10;
24-
reverse = reverse + n%10;
25-
n = n/10;
23+
while(n != 0) {
24+
reverse *= 10;
25+
reverse += n%10;
26+
n /= 10;
2627
}
2728
return reverse;
2829
}
2930

30-
public static void funtioning(int y){
31-
int count =0;
32-
int num = 2;
33-
while(count < y){
34-
if(prime(num) && num == reverse(num)){ // number is prime and it's reverse is same
35-
count++; // counts check when to terminate while loop
36-
System.out.print(num + "\n"); // Print the Palindromic Prime
37-
}
38-
num++; // inrease iterator value by one
31+
public static void functioning(int y) {
32+
if (y == 0) return;
33+
System.out.print(2 + "\n"); // print the first Palindromic Prime
34+
int count = 1;
35+
int num = 3;
36+
while(count < y) {
37+
if(num == reverse(num) && prime(num)) { // number is prime and it's reverse is same
38+
count++; // counts check when to terminate while loop
39+
System.out.print(num + "\n"); // print the Palindromic Prime
3940
}
41+
num += 2; // inrease iterator value by two
42+
}
4043
}
41-
};
44+
}

0 commit comments

Comments
 (0)