Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Provided your <code>X</code> is small enough, you can use the Sieve of Eratosthenes to do it more efficiently. This is ideal for the "primes up to X" case since it maintains a memory of previously discarded primes. It does so by keeping a set of flags for each candidate number, all initially set to true (except for 1, of course).</p> <p>Then you take the first true value (2), output that as a prime, and then set the flags for all multiples of that to false.</p> <p>Then carry on with:</p> <ul> <li>3;</li> <li>5 (since 4 was a multiple of 2);</li> <li>7 (since 6 was a multiple of 2 and 3);</li> <li>11 (since 8 and 10 were multiples of 2 and 9 was a multiple of 3);</li> <li>13 (since 12 was a multiple of 2);</li> <li>17 (since 14 and 16 were multiples of 2 and 15 was a multiple of 3 and 5);</li> <li>and so on.</li> </ul> <p>Pseudo-code would be similar to:</p> <pre><code>def showPrimesUpTo (num): // create array of all true values array isPrime[2..num] = true // start with 2 and go until finished currNum = 2 while currNum &lt;= num: // if prime, output it if isPrime[currNum]: output currNum // also flag all multiples as nonprime clearNum = currNum * 2 while clearNum &lt;= num: isprime[clearNum] = false clearNum = clearNum + currNum // advance to next candidate currNum = currNum + 1 </code></pre> <p>Otherwise, you can do trial division as per your suggestion. The basic idea is to check each number from 2 up to the square root of your target number to see if it's a multiple. In pseudo-code, that would be something like:</p> <pre><code>def isPrime (num): // val is the value to check for factor val = 2 // only need to check so far while val * val &lt;= num: // check if an exact multiple if int (num / val) * val == num: return false // no, carry on val = val + 1 // if no factors found, it is a prime return true </code></pre> <p>The reason you only need to check up to the square root is because, if you find a factor above there, you would have already found the corresponding factor <em>below</em> the square root.</p> <p>For example, <code>3 x 17</code> is <code>51</code>. If you're checking the numbers from 2 through 50 to see if <code>51</code> is prime, you'll find <code>3</code> first, meaning you never need to check <code>17</code>.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload