私は学校でこの問題を書いていますが、いくつか問題があります。実際に素数を計算することはできません。明らかに、番号4のメインからテストを実行すると、4が素数であることがわかります。どのように式を書く必要がありますか?Javaでの再帰を使用した素数の検索
手順は次のとおりです。 (別の再帰関数のラッパーをまたはこの関数を作る)この関数を記述するために
使用再帰
* 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));
}
私の悪いです。編集されました。 – BigJ
作業中の再帰コードを書いたことがありますか? –
私はこの1週間前に始めました。私はまだ学んでいて、しばしば間違いを犯します。ちょうど私が正しい/間違っていることについて何らかのフィードバックを得ようとしています。ありがとう。 – BigJ