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

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

    It's all really just basic uses of Factorization and Square Roots.

    It may appear to be abstract, but in reality it simply lies with the fact that a non-prime-number's maximum possible factorial would have to be its square root because:

    sqrroot(n) * sqrroot(n) = n.

    Given that, if any whole number above 1 and below or up to sqrroot(n) divides evenly into n, then n cannot be a prime number.

    Pseudo-code example:

    i = 2;
    
    is_prime = true;
    
    while loop (i <= sqrroot(n))
    {
      if (n % i == 0)
      {
        is_prime = false;
        exit while;
      }
      ++i;
    }
    

提交回复
热议问题