使用Java

时间:2016-09-12 03:22:48

标签: java recursion

我正在为学校写这个问题而且我有一些问题。我无法得到它来实际计算素数。显然,当我从主编号4进行测试时,当我们都知道它不是时,它说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不是#prime#。

         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));        
}

3 个答案:

答案 0 :(得分:0)

这项任务给了你一个重要的提示:

  

或使此函数成为另一个递归函数的包装器

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);
}

答案 1 :(得分:0)

cdlane 的答案有基本修正。我只是想确保你知道你的尝试在哪里工作。你有两个致命的问题:

  1. 您的递归没有简化。如果你没有击中基本情况(0-3),你会发现相同的号,让你陷入无限循环。
  2. 您的 sqrt 条款既不必要又错误。如果数字的sqrt是偶数,则不能为素数。这应该是阻止递归的测试吗?

答案 2 :(得分:-3)

在素数中,2不能是素数,因为你可以将它除以2并且它不能除以2.因此,如果number%2为0或数字为2,则需要返回假。

如果数字不是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;
    }
相关问题