What is wrong with my isPrime method?
73,266
Solution 1
Your condition should be i * i <= num
private static boolean isPrime(int num)
{
if (num == 2)
return true;
if (num < 2 || num % 2 == 0)
return false;
for (int i = 3; i * i <= num; i += 2)
if (num % i == 0)
return false;
return true;
}
You didn't take number 9 in your consideration so 9<9 will result false. But you need to check 9.
Solution 2
my sample:
public boolean isPrime(int x) {
if (x==1) {
return true;
} else {
for(int i=2;i<=Math.sqrt(x);i++) {
if (x%i==0) return false;
}
}
return true;
}
Solution 3
Java 8: (Example with lambda expression and streams)
public static boolean isPrimeFunctionalStyle(int number) {
return number > 1 &&
IntStream.rangeClosed(2, (int) Math.sqrt(number))
.noneMatch(i -> number % i == 0);
}
Solution 4
Change your code like this ( check condition) :
private static boolean isPrime(int num) {
if (num == 2) return true;
if (num % 2 == 0)
return false;
for (int i = 3; i * i <= num; i += 2)
if (num % i == 0) return false;
return true;
}
Solution 5
Here are some hints:
The main bug is that you never check divisibility by
sqrt(num)
due to an off-by-one error in the loop.The other bug is that you don't consider
2
to be prime (which it is).
Author by
usama8800
Updated on July 02, 2020Comments
-
usama8800 almost 4 years
This is my
isPrime
method:private static boolean isPrime(int num) { if (num % 2 == 0) return false; for (int i = 3; i * i < num; i += 2) if (num % i == 0) return false; return true; }
I put
isPrime(9)
and it returnstrue
. What is wrong with the method? -
Tareq Salah about 9 years@ADG thanks for the hint .. but when the question was asked .. he want to fix specific bug in the code .. I didn't notice case when num=2
-
Stella Lie almost 9 years1 is not a prime number, shall add
|| num == 1
to the second line on the function -
friederbluemle about 8 years@StellaLie Even more generically, numbers smaller than 2 are not prime.
-
ssukienn about 7 yearsI would downvote for putting code with exactly same mistake OP had but I can't. There should be
i * i <= num
-
Popeye over 6 years1 is not a prime number, adjust your sample.
-
Alex Riabov almost 6 yearsWhile this code may answer the question, providing additional context regarding why and/or how this code answers the question improves its long-term value.