Reputation: 3
I'm new here and hopefully, someone may be able to guide me with my problem.
I have to find a number that is both prime and a palindrome such as:
2 3 5 7 11 101 131 151 181 191 313 353 373 383 727 757 787 797 919 929
I believe my problem is in my reverse()
method somehow because when I try to compare numbers in my if
statement, for option1
it displays prime numbers alongside other numbers. Trying to get the first 20 for now.
And sorry if the code is messy, have been working on this for a few hours.
import java.util.Scanner;
public class PalindromePrimeAndMirrorPrime {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String menu = " 1. Display Prime Palindrome"
+ "\n 2. Display mirrored primes"
+ "\n 3. Exit Program";
System.out.println(menu);
int choice = in.nextInt();
//menu((option1(20)));
//reverse(562897498);
//option1(20);
option1(20);
}
public static boolean prime(int num) {
for (int divisor = 2; divisor <= num / 2; divisor++) {
if (num % divisor == 0) {
return false;
}
}
return true;
}
public static void option1(int y){
int numPerLine=10;
int count =0;
int num = 2;
while(count <= y){
if(prime(num) && num == reverse(num)){ //main issue is here i think it doesnt compare it properly?
count++;
System.out.print(num + " ");
if(count%numPerLine==0){
System.out.println("");
}
}
num++;
}
}
public static int reverse(int x){
int y = x;
while(y!=0){
System.out.print(y%10 + "");
y/=10;
}
//System.out.println();
return x;
}
}
Upvotes: 0
Views: 308
Reputation: 5629
Yes your problem is with the reverse function
public static int reverse(int x){
int y = x;
while(y!=0){
System.out.print(y%10 + "");
y/=10;
}
//System.out.println();
return x;
}
You are not actually reversing x
but returning the same value.
You might want to create a reversed number and then return that.
public static int reverse(int x){
int y = 0;//create the reveresed number here
while(x!=0){
y = y * 10 + x % 10;
x/=10;
}
return y;
}
A small optimisation to your isPrime
would be to check untill it's square root instead of /2
.
for (int divisor = 2; divisor * divisor <= num; divisor++)
Upvotes: 2