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

前端 未结 13 1098
春和景丽
春和景丽 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条回答
  •  萌比男神i
    2020-11-22 03:02

    Given any number n, then one way to find its factors is to get its square root p:

    sqrt(n) = p
    

    Of course, if we multiply p by itself, then we get back n:

    p*p = n
    

    It can be re-written as:

    a*b = n
    

    Where p = a = b. If a increases, then b decreases to maintain a*b = n. Therefore, p is the upper limit.

    Update: I am re-reading this answer again today and it became clearer to me more. The value p does not necessarily mean an integer because if it is, then n would not be a prime. So, p could be a real number (ie, with fractions). And instead of going through the whole range of n, now we only need to go through the whole range of p. The other p is a mirror copy so in effect we halve the range. And then, now I am seeing that we can actually continue re-doing the square root and doing it to p to further half the range.

提交回复
热议问题