Palindrome Prime,比较反转数字

时间:2015-11-13 06:08:26

标签: java

想先说嗨!我是新来的,希望有人可以指导我解决我的问题。

我必须找到一个素数和回文数 如:

  

2 3 5 7 11 101 131 151 181 191 313 353 373 383 727 757 787 797 919 929

我认为我的问题出现在我的reverse()方法中,因为当我尝试比较if语句中的数字时,对于option1,它会显示素数和其他数字。试着现在获得前20名。

任何帮助都将不胜感激。

对不起,如果代码很乱,已经在这个问题上工作了几个小时。

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;
    }   
}

1 个答案:

答案 0 :(得分:2)

是的,问题在于反向功能

public static int reverse(int x){
    int y = x;
    while(y!=0){
        System.out.print(y%10 + "");
        y/=10;
    }
    //System.out.println();
    return x;
}

您实际上并没有倒转x,而是返回相同的值。

您可能想要创建一个反转的数字然后返回它。

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;
}

isPrime的一个小优化是检查直到它而不是/2

for (int divisor = 2; divisor * divisor <= num; divisor++)