【发布时间】:2017-01-19 10:56:06
【问题描述】:
我正在为学校写这个问题,但我遇到了一些问题。我无法让它实际计算素数。显然,当我从 main 用数字 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 squared % 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));
}
【问题讨论】:
-
我的错。已编辑。
-
你写过任何有效的递归代码吗?
-
我上周刚开始。我还在学习,经常犯错误。只是想获得一些关于我做对/错的反馈。谢谢。
-
在这种情况下不需要使用递归,因为它只会执行一次指令块 isPrime 方法作为最后一个数字作为参数值永远不会改变总是得到相同的结果。
-
我明白你在说什么。也许循环会更好。我只是想按照说明进行操作。 (见编辑过的问题)