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

前端 未结 13 1090
春和景丽
春和景丽 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:20

    Any composite number is a product of primes.

    Let say n = p1 * p2, where p2 > p1 and they are primes.

    If n % p1 === 0 then n is a composite number.

    If n % p2 === 0 then guess what n % p1 === 0 as well!

    So there is no way that if n % p2 === 0 but n % p1 !== 0 at the same time. In other words if a composite number n can be divided evenly by p2,p3...pi (its greater factor) it must be divided by its lowest factor p1 too. It turns out that the lowest factor p1 <= Math.square(n) is always true.

提交回复
热议问题