Interview Question - How to detect whether one number is prime

如何判断输入的数,是否为 Prime

My code:

public boolean isPrime(int x) {
    if (x <= 1) {
        return false;
    }
    else if (x == 2) {
        return true;
    }
    
    for (int i = 3; i * i <= x; i += 2) {
        if (x % i == 0) {
            return false;
        }
    }
    return true;
}

首先,除了 2 以外,其他质数都是奇数。
其次 , i * i <= n

Anyway, Good luck, Richardo! -- 09/28/2016

你可能感兴趣的:(Interview Question - How to detect whether one number is prime)