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 returns true. What is wrong with the method?
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.
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;
}
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);
}
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
2to be prime (which it is).
(Late) Sidenode:
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;
}
This code is missing 2; 2 is a primenumber. Everything dividable by 2 isn't, except the 2 - so, use:
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;
}
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;
}
the loop condition with i * i < num should be i * i <= num
the loop is never executed so it returns directly true
The loop does not run. It gets terminated in the very first value of i because 3 x 3 = 9 it does not meet the condition i * i < n
for (int i = 3; i * i < num; i += 2)
if (num % i == 0) return false;
i * i is 9, and 9 in not less than 9, thus for loop is not run.
you can simply use if and else statement to check to see if the number is prime. There is a pattern, all the numbers are either multiples of either 2 or 3 once your number reach certain limits.
public static boolean isPrime2 (int n)
{
if (n == 1) {
return false;
} else if (n == 2 || n==3) {
return true;
} else if (n>2) {
if(n % 2 ==0 || n % 3 == 0) {
return false;
}
}
return true;
}
public static boolean isPrime (int number) {
if(number < 2) {
return false;
}
int check = (int) Math.sqrt(number);
for(int i = 2; i <= check; i++) {
if(number % i == 0) {
return false;
}
}
return true;
}
来源:https://stackoverflow.com/questions/20798391/what-is-wrong-with-my-isprime-method