[英]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的答案有基本的更正。 我只是想確保您知道嘗試失敗的地方。 您有兩個致命問題:
在質數中,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.