在 Java 中使用 IsPrime 方法

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/35122818/
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-02 23:45:37  来源:igfitidea点击:

Using IsPrime method in Java

java

提问by Harshit Singh

This is my code to use IsPrime method to determine total number of primes between 0 and 1000 and print the total number of primes at last. Can anyone tell what's wrong with the code.

这是我使用 IsPrime 方法确定 0 到 1000 之间的素数总数并最后打印素数总数的代码。谁能告诉代码有什么问题。

public static void main(String[] args) {
    int z=0; 
    // z is the variable that holds total number of primes
    //n is divisor
    //i is dividend

    if (isPrime(i)) {
        z++;
    }
    System.out.print(z+"\n");
}

public static boolean isPrime(int n){
             { 
    for(i=0; i<1000; i++)
    {
        for(n=0; n<i; n++)
            if(i%n==0) 
                return false;
            else 
                return true;
        }
    }
}

Thanks in advance

提前致谢

回答by sparkhee93

Formatting it might help you discover the error.

格式化它可能会帮助您发现错误。

I see a few things that's wrong with your code:

我发现您的代码有一些问题:

  1. From what I can see, you have an extra open curly bracket in your isPrimemethod.
  2. iisn't declared in your main method.
  3. You need to wrap your if(isPrime(i))statement inside a for loop that goes from 0 to 1000. Like the following:

    for (int i = 0; i <= 1000; i++) {
        if (isPrime(i))
            z++;
    }
    

    That way, it will be actually checking all the prime numbers from 0 to 1000

  4. For good coding practices, I would name your zvariable to be something like counterso that it's clear what that variable is supposed to be doing. iin for-loop is okay since that's a common way to index through the loop.
  5. You can also use several tactics to optimize your code. You can use Math.sqrt()function, as well as start your for loop from 3 and go up by increment of 2 (since any even number will be dividable by 2) and initialize your counter from 1 since 2 will already be a prime number.
  1. 据我所知,您的isPrime方法中有一个额外的开大括号。
  2. i未在您的主要方法中声明。
  3. 您需要将您的if(isPrime(i))语句包装在一个从 0 到 1000 的 for 循环中。如下所示:

    for (int i = 0; i <= 1000; i++) {
        if (isPrime(i))
            z++;
    }
    

    这样,它实际上会检查从 0 到 1000 的所有质数

  4. 对于良好的编码实践,我会将您的z变量命名为类似counter这样的名称,以便清楚该变量应该做什么。i在 for 循环中是可以的,因为这是循环索引的常用方法。
  5. 您还可以使用多种策略来优化代码。您可以使用Math.sqrt()函数,也可以从 3 开始 for 循环,然后以 2 为增量递增(因为任何偶数都可以被 2 整除)并从 1 初始化您的计数器,因为 2 已经是质数。

回答by Naveen Bathina

public static boolean isPrime(int n){
    int factors = 0;
    for(int i = 1; i <= n; i++){
        if(n % i == 0) // ensure that you mod n not i
        factors++;
     }
    // if factors count is equals to 2 then it is prime number else it's not prime number
    if(factors == 2)
        return true;
    else
        return false;
}

Check this modified code once for your reference.

检查此修改后的代码一次以供您参考。

回答by LuvnJesus

I think you had a few things turned around.

我想你已经扭转了一些事情。

Why not loop from 1 to 1000 in your primary function and then use the isPrime function to determine if each number is prime.

为什么不在主函数中从 1 到 1000 循环,然后使用 isPrime 函数来确定每个数字是否为素数。

In the isPrime function, you count from 2 to 1/2 the value of the number and do the divisions to determine if it is prime. Return False if it is divisible.

在 isPrime 函数中,您从 2 数到 1/2 的值并进行除法以确定它是否为素数。如果可整除,则返回 False。

public static void main(String[] args) {
  int z=0; 
  for (i=1;i<=1000;i++) {
       if (isPrime(i))
       {
           z++;
       }
    }
    System.out.print(z+"\n");
}
public static boolean isPrime(int n){
        for(i=2; i<=n/2; i++)
        {
           if(n%i==0) return false;
        }
        return true;
}

回答by Dave

You need to define the variable "i" before you pass it to the isPrime() method in main(). It seems as though whoever wrote the code did not fully understand what a prime number was. According to wikipedia "A prime number (or a prime) is a natural number greater than 1 that has no positive divisors other than 1 and itself. " With this in mind you need to make sure that the value you pass to the isPrime() method is greater than 1. After look at your code I made some changes. I made the isPrime() method return false if the input value is <=1. Also, I made the isPrime() method return true if the input value is 2. I made other changes in the code that would make the for statement operate n-1 times because that is all that is needed to find out if the number is prime because all numbers are divisible by themselves. Also the for statement starts at the value 2. Your if-then-else return statements within the for loop is illogical because it will return a value without going through the entire loop. You did not need the inner for loop.
Here's a link on prime numbers

您需要先定义变量“i”,然后再将其传递给 main() 中的 isPrime() 方法。似乎编写代码的人并没有完全理解质数是什么。根据维基百科“质数(或质数)是大于 1 的自然数,除了 1 和它本身之外没有正除数。”考虑到这一点,您需要确保传递给 isPrime() 的值方法大于 1。查看您的代码后,我做了一些更改。如果输入值 <=1,我让 isPrime() 方法返回 false。此外,如果输入值为 2,我让 isPrime() 方法返回 true。我对代码进行了其他更改,使 for 语句运行 n-1 次,因为这就是确定数字是否为素数,因为所有数字都可以被自己整除。此外,for 语句从值 2 开始。for 循环中的 if-then-else 返回语句是不合逻辑的,因为它会在不经过整个循环的情况下返回一个值。您不需要内部 for 循环。
这是质数的链接

Here is the new code:

这是新代码:

public class AreaComparison {

    /**
     * Starts the program.
     *
     * @param command line arguments
     */

    public static void main(String[] args) {
        int z = 0;
        int i = 2;
    // z is the variable that holds total number of primes
        //n is divisor
        //i is dividend

        if (isPrime(i)) {
            z++;
        }
        System.out.print(z + "\n");
    }

    public static boolean isPrime(int n) {
        if (n <= 1) {
            return false;
        }
        if(n == 2){
            return true;
        }

        for (int i = 2; i < n; i++) {

            if (n % i == 0) {
                return false;
            }

        }
        return true;
    }

}

回答by John Ephraim Tugado

This will count the number of primes based on this linkand your original answer...

这将根据此链接和您的原始答案计算素数...

public static void main(String[] args) {
    int isPrimeCount = 0;

    for(i=0; i<1000; i++)
    {
        if(Check_Prime(i))
        {
          isPrimeCount++;
        }
        System.out.println(isPrimeCount);
    }
}

private static boolean Check_Prime(int number) {
    int i;
    for (i = 2; i <= number - 1; i++)
    {
        if (number % i == 0)
        {
           return false;
        }
    }
    if (i == number)
    {
        return true;
    }
    return false;
}