[Java]检查一个数是否为素数,使用额外的 isPrime 标志不起作用

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/47965404/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 09:54:04  来源:igfitidea点击:

[Java]Checking if a number is prime, not working by using extra isPrime flag

javaprimes

提问by XIAOLONG LI

I asked this question on 2017. I updated on 2020 under these codes.

我在 2017 年问了这个问题。我在 2020 年根据这些代码进行了更新。

This question is checking the number is prime or not, of course there are already different answers. But I have tried all day, I couldn't find why my methods is not working properly.

这个问题是检查数字是不是质数,当然已经有不同的答案了。但是我已经尝试了一整天,我找不到为什么我的方法不能正常工作。

public class PrimeNum 
{
    private static boolean isPrime;
    private static Scanner input;

    public static void main(String[] args)
    {
        input = new Scanner(System.in);
        System.out.println("Enter a prime number ( you think ) : ");
        int num = input.nextInt();

        isPrime = false;
        for(int divisor = 2; divisor < num / 2; divisor++) {
            if(num % divisor == 0)
            {

                isPrime = false;
            }
            isPrime = true;
        }
        if(isPrime)
        {
            System.out.println("Prime");

        }
        else
        {
            System.out.println("Not a prime");
        }
    }
}

Update on May 2020:

2020 年 5 月更新:

I realized that I was asking a stupid question. The main reason is not working here:

我意识到我在问一个愚蠢的问题。主要原因在这里不起作用:

           isPrime = false;
           for(int divisor = 2; divisor < num / 2; divisor++) {
                if(num % divisor == 0)
                {

                    isPrime = false;
                }
                isPrime = true; // May 2020: no matter what num, it will become true here.
            }

  • divisor < num / 2 -> it will not check number 3, 4... because divisor starts from 2, and never less than 3/2 = 1, 4/2=2. here needs to change to divisor < num.
  • divisor < num / 2 -> 它不会检查数字 3, 4... 因为除数从 2 开始,并且永远不会小于 3/2 = 1, 4/2=2。这里需要改为除数 < num。
  • isPrime = true -> No matter what num is, isPrime will become true. So I need to simply add else round isPrime = true.
  • isPrime = true -> 无论 num 是什么,isPrime 都会变为 true。所以我需要简单地添加 else 轮 isPrime = true。
  • We actually only need to check if the number is not itself, and if it is divisible by divisor then it is false.
  • 我们实际上只需要检查数字是否不是它本身,如果它可以被除数整除则它是假的。
  • always good to put function outside main, so that we can use it. The final solution:

    import java.util.*;
    class Prime {
        public static void main(String[] args){
            Scanner input = new Scanner(System.in);
            System.out.println("Enter a prime number ( you think ) : ");
            int num = input.nextInt();
            if(ifPrime(num)) {
                 System.out.println(num + " is a prime number");
            }
            else {
                System.out.println(num + " is a NOT prime number");
            }
        }
        private static boolean ifPrime(int num) {
    
            for(int divisor = 2; divisor < num; divisor++) {
                if( num != divisor && num % divisor == 0){
                    return false;
                }
            }
            return true;
        }
    }
    
  • 将函数放在 main 之外总是好的,这样我们就可以使用它。最终的解决方案:

    import java.util.*;
    class Prime {
        public static void main(String[] args){
            Scanner input = new Scanner(System.in);
            System.out.println("Enter a prime number ( you think ) : ");
            int num = input.nextInt();
            if(ifPrime(num)) {
                 System.out.println(num + " is a prime number");
            }
            else {
                System.out.println(num + " is a NOT prime number");
            }
        }
        private static boolean ifPrime(int num) {
    
            for(int divisor = 2; divisor < num; divisor++) {
                if( num != divisor && num % divisor == 0){
                    return false;
                }
            }
            return true;
        }
    }
    
  • 回答by Mureinik

    The main issue here is that you overwrite the value of isPrimein every iteration, so if the last divisor you check does not divide num, you interpret it as a prime.

    这里的主要问题是您isPrime在每次迭代中都覆盖了 的值,因此如果您检查的最后一个除数没有被除num,您将其解释为素数。

    A better approach would be to assume a number is a prime until proven otherwise (i.e., until you find a divisor for it). Once you've found such a divisor, you can breakout of the loop - the number isn't a prime, and there's no reason to keep on checking it:

    更好的方法是假设一个数是素数,除非另有证明(即,直到找到它的除数)。一旦找到这样的除数,您就可以break跳出循环 - 该数字不是质数,并且没有理由继续检查它:

    isPrime = true;
    for(int divisor = 2; divisor <= num / 2; divisor++) {
        if (num % divisor == 0) {
            isPrime = false;
            break; // num is not a prime, no reason to continue checking
        }
    }
    

    回答by pjpj

    In your code

    在你的代码中

    for(int divisor = 2; divisor < num / 2; divisor++) {
        if(num % divisor == 0)
        {
    
            isPrime = false;
        }
        isPrime = true;
    }
    

    If isPrime = false, then you make it true again!

    如果 isPrime = false,那么你又让它为真!

    You can consider this:

    你可以这样考虑:

        isPrime = true;
        for(int divisor = 2; divisor < num / 2; divisor++) {
            if(num % divisor == 0)
            {
                isPrime = false;
                break;
            }
        }
    

    回答by amk

    Try with this:

    试试这个:

    public class prime{
    public static void main (String args[]){
    int n1=100, n2=1000;
    int c=0;
    for(int i=n1; i<=n2; i++)
        if(isPrime(i)==true)
            c++;
        System.out.print(c);
    }
    public static boolean isPrime(int number)
    {
    
        for(int j=2; j<number; j++) //u go from number+1 to number to check 
                                    //if it can be divided by any other value.
            if(number % j ==0) //if there is 1 other number that divides it then
                               //it returns false.
                return false;
    
            return true; //else it returns true.
    }
    }
    

    回答by CapLuo

    public class PrimeNum {

    公共类 PrimeNum {

    private static boolean isPrime;
    private static Scanner input;
    
    public static void main(String[] args) {
        input = new Scanner(System.in);
        System.out.println("Enter a number ( you think ) : ");
        String ch = input.next();
    
        if (isNumeric(ch)) {
            int num = Integer.parseInt(ch);
            isPrime = true;
            if (num > 1) {
                for (int divisor = 2; divisor * divisor <= num; divisor++) {
                    if (num % divisor == 0) {
                        isPrime = false;
                        break;
                    }
                }
            } else {
                isPrime = false;
            }
    
            if (isPrime) {
                System.out.println("Prime");
    
            } else {
                System.out.println("Not a prime");
            }
        } else {
            System.out.println("Should input a number");
        }
    }
    
    public static boolean isNumeric(String str) {
        Pattern pattern = Pattern.compile("[0-9]*|\-[0-9]*");
        Matcher isNum = pattern.matcher(str);
        if (!isNum.matches()) {
            return false;
        }
        return true;
    }
    

    }

    }