繁体   English   中英

在Java中使用递归查找素数

[英]Finding a prime number using recursion in Java

我正在为学校写这个问题,对此有一些疑问。 我无法实际计算素数。 显然,当我用数字4从main运行测试时,它说4是素数,而我们都知道不是。 我该如何写方程式?

说明如下。

使用RECURSION编写此函数(或使该函数成为另一个递归函数的包装器)

 * a number is prime if it is divisible only by itself and 1 
 * (that is, if it is not divisible by any number between * itself and 1; 
 * we can optimize and just check between 2 and the square root of the number).
 * by convention, 1 is NOT prime
 * this function returns true if its parameter is prime, false otherwise.
 * One way to do this is to test all numbers between 2 and n; if any of them     
 * divides it, then it is not prime. If you reach the end, then it is.
 * Examples:
 * isPrime(1) => false
 * isPrime(2) => true
 * isPrime(3) => true
 * isPrime(4) => false
 */



public static boolean isPrime(int n)
{
    if (n == 0 || n == 1) { 
        return false; 
    } if (n == 2 || n == 3) { 
        return true; 
    } if (Math.sqrt(n) % 2 == 0) { 
        return true;
    }else
        return isPrime(n);
    }

以下代码来自我的教授用来对该程序进行评分的grader.java。 有一些对isprime方法的调用。 它似乎总是挂在4上(我明白为什么... 4平方%2 == 0),而4不是质数。

         public void testIsPrime()
{
    Assert.assertEquals("1 is not prime", false,Assignment4.isPrime(1));
    Assert.assertEquals("2 is prime", true,Assignment4.isPrime(3));
    Assert.assertEquals("4 is not prime", false,Assignment4.isPrime(4));
    Assert.assertEquals("7 is prime", true,Assignment4.isPrime(7));
    Assert.assertEquals("9 is not prime", false,Assignment4.isPrime(9));
    Assert.assertEquals("35 is not prime", false,Assignment4.isPrime(35));
    Assert.assertEquals("37 is prime", true,Assignment4.isPrime(37));        
}

该作业为您提供了重要的提示:

或将此函数包装为另一个递归函数

public static boolean isPrime_helper(int number, int divisor)
{
    /* write code to return true if divisor is > square root of number */
    /* which can also be expressed divisor squared is > number */

    /* write code here to test if divisor divides number without remainder */
    /* and return false if it does.  Otherwise: */

    return isPrime_helper(number, divisor + 2);
}

public static boolean isPrime(int number)
{
    /* deal with the special cases 2, < 2, and even numbers here */
    /* Otherwise: */

    return isPrime_helper(number, 3);
}

cdlane的答案有基本的更正。 我只是想确保您知道尝试失败的地方。 您有两个致命问题:

  1. 您的递归没有简化。 如果您还没有达到基本情况(0-3),则以相同的数字重复出现,从而陷入无限循环。
  2. 您的sqrt子句既不必要又错误。 如果数字的平方数是偶数,则不能为质数。 这应该是停止递归的测试吗?

在质数中,2不能是质数,因为您可以将其除以2并且不能将其除以2。因此,如果number%2为0或number为2,则需要返回false。

如果数字不是2或无法将其除以0,则可以在函数内部使用for循环检查其他数字。

看一下下面的代码,它可以帮助您了解正在发生的事情:

public boolean isPrime (int number){
    if ((number%2)==0 && number != 2) {
        return false;
    }
    else {
        for (int i =3; i*i<number; i++ )
        {
            if (number%i ==0)
                return false;
        }
        return true;
    }

暂无
暂无

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

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