0

我需要编写一个找到数字因数的程序。如果是素数,我只需要说它是素数,否则我需要显示因子。我还需要这样做,所以如果是其中一个,它会显示一个特定的声明。我可以弄清楚分解,但如果数字是素数,我不知道如何编写显示。这必须使用 JOptionPane 来完成,我非常困惑。

当前代码:

{
    String intro = "Hello!\nThis program will ask you to enter a number and will then tell you whether or not it is prime.\n"
            + "If the number is prime, it will be shown and you will be told it is prime.\n"
            + "If the number is not prime, it willl be shown followed by it's prime decomposition.\n\n"
            + "For example, for 41: The number 41 is prime\n"
            + "For example, for 105: The number 105 will be shown, followed by 3 X 5 X 7";
    JOptionPane.showMessageDialog(null, intro, "Prime Decomposer, Introduction",1);

    String numPrompt = JOptionPane.showInputDialog(null, "Please enter any positive integer.\n"
                    + "The number must be positive, and CANNOT be a decimal value such as 1.5\n\n"
                    + "For example, if you wanted to enter the number 12,"
                    + " you would enter: 12", "Prime Decomposer, Integer Entry",1);
    int userNum = Integer.parseInt(numPrompt);
    int iteration = 0;
    int factoredNum = userNum;
    String decomposition = "";
    for(iteration = 2; iteration <= userNum; iteration++)
        {
            while(factoredNum % iteration == 0)
            {
                decomposition += iteration + " ";
                factoredNum /= iteration;
            }

        }
        JOptionPane.showMessageDialog(null, "The number "+userNum+" is not prime. Its decomposition is "+decomposition);
}
4

1 回答 1

0

有点难看,但我认为这会奏效。

int isPrime = 0;    
for(iteration = 2; iteration <= userNum; iteration++)
    {
        while(factoredNum % iteration == 0)
        {
            if(iteration<userNum){
                isPrime++;
            }
            decomposition += iteration + " ";
            factoredNum /= iteration;
        }

    }
    if(isPrime==0){
       JOptionPane.showMessageDialog(null, "The number "+userNum+" is prime. Its decomposition is "+decomposition);
    }else{
       JOptionPane.showMessageDialog(null, "The number "+userNum+" is not prime. Its decomposition is "+decomposition);
    }
于 2016-03-07T23:30:46.790 回答