Determination of prime numbers

ACwing866. Primes trial division determination

Defined prime numbers: a number n, if it can not be [2,n-1]all numbers within divisible, n is a prime number is.

Of course, we can range from [2,n-1]down to[2,根号n]

Certify as follows:

Assumptions n=a*b, there is min(a,b) <= 根号n, so a <= blong as the check [2,根号n]number in. If n is not a prime number, you can find a a. If there is not this a, then [根号n,n-1]inside there is no b

Algorithm is as follows:

bool is_prime(int n)
{
    if (n <= 1)
        return false;  // 1不是素数
    for (int i = 2; i * i <= n; i++)  // 比for (int i = 2; i <= sqrt(n); i++) 更好
        if (n % i == 0)  // 能整除,不是素数
            return false;
    return true;
}

Guess you like

Origin www.cnblogs.com/WalterJ726/p/12319305.html