Why do we check up to the square root of a prime number to determine if it is prime?

前端 未结 13 898
春和景丽
春和景丽 2020-11-22 02:24

To test whether a number is prime or not, why do we have to test whether it is divisible only up to the square root of that number?

相关标签:
13条回答
  • 2020-11-22 03:21

    To test the primality of a number, n, one would expect a loop such as following in the first place :

    bool isPrime = true;
    for(int i = 2; i < n; i++){
        if(n%i == 0){
            isPrime = false;
            break;
        }
    }
    

    What the above loop does is this : for a given 1 < i < n, it checks if n/i is an integer (leaves remainder 0). If there exists an i for which n/i is an integer, then we can be sure that n is not a prime number, at which point the loop terminates. If for no i, n/i is an integer, then n is prime.

    As with every algorithm, we ask : Can we do better ?

    Let us see what is going on in the above loop.

    The sequence of i goes : i = 2, 3, 4, ... , n-1

    And the sequence of integer-checks goes : j = n/i, which is n/2, n/3, n/4, ... , n/(n-1)

    If for some i = a, n/a is an integer, then n/a = k (integer)

    or n = ak, clearly n > k > 1 (if k = 1, then a = n, but i never reaches n; and if k = n, then a = 1, but i starts form 2)

    Also, n/k = a, and as stated above, a is a value of i so n > a > 1.

    So, a and k are both integers between 1 and n (exclusive). Since, i reaches every integer in that range, at some iteration i = a, and at some other iteration i = k. If the primality test of n fails for min(a,k), it will also fail for max(a,k). So we need to check only one of these two cases, unless min(a,k) = max(a,k) (where two checks reduce to one) i.e., a = k , at which point a*a = n, which implies a = sqrt(n).

    In other words, if the primality test of n were to fail for some i >= sqrt(n) (i.e., max(a,k)), then it would also fail for some i <= n (i.e., min(a,k)). So, it would suffice if we run the test for i = 2 to sqrt(n).

    0 讨论(0)
提交回复
热议问题