Shall I take the cailed square root of n to test for a prime?

233 Views Asked by At

Algorithm:

  1. square root of $n$
  2. test all primes lower than the square root of $n$ if they go evenly up into $n$; if not, $n$ is a prime

But do I have to take ceil$(n)$ or floor$(n)$ as the square root?

2

There are 2 best solutions below

0
On

Don't have to take the square root.

If you are testing a series of primes p, stop when n/p < p.

0
On

You have to check for primes only up to floor$(\sqrt n)$.

That's because if $p>\sqrt n$ and $pq=n$, then $q<\sqrt n<p$,

so you would have found a factor of $n$ before you got up to testing $p$ dividing $n$.