简体   繁体   English

搜索素数的方法

[英]Method to search for prime numbers

I need to build a method that calculates prime numbers. 我需要建立一种计算素数的方法。

I'm testing it and it's giving me the wrong answers and I don't know how to solve it! 我正在测试它,它给了我错误的答案,我不知道如何解决! For example, it returns true to 98262679 instead of false . 例如,它返回true到98262679而不是false Where is my mistake? 我的错误在哪里?

public static boolean itsPrime(int nbTest){   // Tests for prime numbers method

        boolean prime = false;

        if (nbTest <= 1){
             return false;
        } else if (nbTest == 2){     // Two is prime   
            return true;
        } else if ((nbTest != 2) && (nbTest % 2 == 0)){       // Evens except number 2
            return false;                                     // are not prime
        } else if (nbTest % 2 != 0){    // For all remaining odds
            for(int i = 3; i <= Math.sqrt(nbTest); i = i+2){ 
                if (nbTest % i == 0){
                    prime = false;
                } else {
                    prime = true;
                }
            }   
        }

        return prime; 
    }

I'm learning Java and my professor asked us to construct the method itsPrime was based on this: 我正在学习Java,我的教授要求我们构造基于此的itsPrime方法:

    For the first subtask, write a function `itsPrime` that takes an `int` 
            as argument and returns a `boolean`, `true` if the argument integer is prime 
        and `false` otherwise.

                To test whether an integer x is prime, one can proceed as follows:
                all integers less than or equal to 1 are not prime;
                2 is prime;
                all other even integers are not prime;
                for all remaining integers (obviously odd), search for a divisor:

                loop from 3 to the square root of the integer x (The square root of x can 
    be computed as ‘‘Math.sqrt(x)'' in Java.); if the remainder of the integer 
division of x by the loop index is zero, then x is not prime;
 if all remainders were non-zero at the end of the loop, then x is prime; 

You should stop once you here: 您一旦在这里就应该停止:

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

Delete the prime variable (it is an unnecessary step, see below). 删除prime变量(这是不必要的步骤,请参见下文)。

Change the for loop: 更改for循环:

for(int i = 3; i <= Math.sqrt(nbTest); i = i+2){ 
    if (nbTest % i == 0){
        prime = false;
    } else {
        prime = true;
    }
}

To this: 对此:

for(int i = 3; i <= Math.sqrt(nbTest); i = i+2)
    if (nbTest % i == 0)
        return false;

This simply breaks out of the function early if it isn't prime (if a factor has been found). 如果不是素数(如果已找到一个因数),这会很早就脱离该函数。

I know the answer is there somewhere in all the answers above, but I think that each require an explanation. 我知道上述所有答案中都有答案,但是我认为每个答案都需要解释。

Here's a summary of all the enhancements you could make to your code: 这是您可以对代码进行的所有增强的摘要:

1) Don't declare a boolean to return, since you are already returning true or false throughout your code. 1)不要声明要返回的布尔值,因为您已经在整个代码中返回了true或false。 Remove this line from your code (call it [1]): 从您的代码中删除此行(将其命名为[1]):

boolean prime = false;

You'll see why after you've fixed the rest of your function. 修复其余功能后,您将看到为什么。 Comment it out if desired, for now. 暂时将其注释掉。

2) In your second else if , let's call it [2], you have: 2)在第二个else if ,我们称它为[2],您具有:

else if ((nbTest != 2) && (nbTest % 2 == 0)){
    return false;
}

You already checked if nbTest is 2 in your first else if , so you don't need to check if it's not 2 again. 您已经在第一个else if检查了if nbTest is 2 ,因此您无需再次检查其是否不是2。 If it entered the first if else , your function will return true . 如果输入的第一个if else ,你的函数将返回true When a function returns, it is done. 当一个函数返回时,它就完成了。 It returns the value to the caller and the rest of the code is not executed. 它将值返回给调用方,其余代码未执行。

Thus, you may replace that second if else , [2], with: 因此,你可以更换第二if else ,[2],其中:

else if (nbTest % 2 == 0) { // all other even integers are not prime
    return false;
}

3) If you enter third else if , this means that the rest of the code above already executed, and it either returned, or the program continued. 3)如果您输入else if第三,则意味着上面的其余代码已经执行,或者返回,或者程序继续执行。

You may replace that third else if (nbTest % 2 != 0){ for: else if (nbTest % 2 != 0){对于:

else {

4) This is the one error that you really have to make your function return the wrong answer (call this snippet [4]): 4)这是您真正要使函数返回错误答案的错误(调用此代码段[4]):

if (nbTest % i == 0){
    prime = false;

If you find that the number you are testing is divisible (ie the remainder is zero), you are done. 如果发现要测试的数字是可分割的(即余数为零),则操作完成。 You definitely know that it is not prime. 您肯定知道它不是素数。

You may replace this code, [4], with: 您可以将以下代码[4]替换为:

if(nbTest % counter == 0) {
    return false;
}

Thus, returning false. 因此,返回false。 It is not a number. 这不是数字。 And the function does not keep executing. 并且该功能不会持续执行。 Your error was continuing execution after the function finds out that your input is not prime. 函数发现您的输入不是素数后,您的错误是继续执行。

Finally, you may leave your return true at the end of the function body. 最后,您可以在函数主体的末尾保留自己的return true If the function never returned from the previous tests, or from the loop, it has to be a prime number. 如果函数从以前的测试或循环中从未返回过,则它必须是质数。 Remember that first line I told you to remove? 还记得我告诉您删除的第一行吗? The boolean declaration? 布尔声明? Since you never return a value from a variable, you just return true or false , you don't need that [1] line. 由于您从不从变量返回值,因此只返回truefalse ,因此不需要该[1]行。

As an extra, a good read on finding prime numbers, which you might want to share with your professor: 另外,您还可以阅读有关寻找质数的好书,您可能希望与教授分享:

https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes

You shouldn't keep testing for primality once prime has been set to false for a number. 一旦将数字的prime设置为false,就不应继续测试primity。

Replace: 更换:

if (nbTest % i == 0){
    prime = false;

with: 有:

if (nbTest % i == 0){
    return false;

And the last test is useless, you can just keep a basic else: 最后的测试是没有用的,您可以保留其他基本内容:

else if (nbTest % 2 != 0){ => else {

Your for loop is not correct. 您的for循环不正确。

A prime number is a number which is divisible by 1 and itself only. 质数是一个只能被1整除的数字。 So, if a number A is divisible by any other number except 1 and itself, then A is a nonprime. 因此,如果数字A可以除1和本身以外的任何其他数字整除,那么A是非质数。

Just replace your for loop with the one below 只需将您的for循环替换为下面的一个

for(int i = 3; i <= Math.sqrt(nbTest); i = i+2) {
    if (nbTest % i == 0)
      return false;
}

Once it is found that nbTest is divisible by some number, there is not point in continuing the loop. 一旦发现nbTest可被某个数整除,就没有必要继续循环了。 Return `nbTest is nonprime, then and there. 返回`nbTest是非素数,然后到那里。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM