Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Question:</p> <blockquote> <p>Find the sum of all the primes below two million.</p> </blockquote> <p>It's a simple <a href="http://en.wikipedia.org/wiki/Sieve_of_Eratosthenes" rel="nofollow noreferrer">sieve</a>. You should read about it but the general idea is to iterate over each number - if the value at index number is <code>0</code>, it's prime and you mark off multiples of that number (since all those multiples <em>must not</em> be prime). Ignore if it's <code>1</code> (composite). I'll provide some comments to explain what this code in particular is doing,</p> <pre><code>marked = [0] * 2000000 # &lt;- just set up the list value = 3 # &lt;- starting at 3 then checking only odds s = 2 # &lt;- BUT include 2 since its the only even prime while value &lt; 2000000: if marked[value] == 0: # &lt;- if number at index value is 0 it's prime s += value # so add value to s (the sum) i = value # &lt;- now mark off future numbers that are multiples of while i &lt; 2000000: # value up until 2mil marked[i] = 1 # &lt;- number @ index i is a multiple of value so mark i += value # &lt;- increment value each time (looking for multiples) value += 2 # &lt;- only check every odd number print s </code></pre> <p>Two optimizations for this code:</p> <ol> <li>The initial value of <code>i</code> could be set to <code>value*value</code> == <code>value**2</code></li> <li>Could easily change this to use a list of length 1 million since we already know no evens are primes</li> </ol> <p><strong>EDIT:</strong></p> <p>While I hope my answer helps explain operations of sieves for future visitors, if you are looking for <em>a very fast sieve implementation</em> please refer to <a href="https://stackoverflow.com/questions/2068372/fastest-way-to-list-all-primes-below-n-in-python">this question</a>. Great performance analysis by unutbu and some excellent algorithms posted by Robert William Hanks!</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. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      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