Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is wrong with my isPrime method?

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?

like image 326
usama8800 Avatar asked Dec 27 '13 09:12

usama8800


2 Answers

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.

like image 180
Tareq Salah Avatar answered Nov 15 '22 22:11

Tareq Salah


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;
}
like image 36
K.Hayoev Avatar answered Nov 15 '22 22:11

K.Hayoev