Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Tried to make a non-loop version just for fun. It came out like this:</p> <pre><code>def erathostenes(n): def helper_function(num_lst, acc): if not num_lst: return acc if len(num_lst) == 1: acc.append(num_lst[0]) return acc num = num_lst.pop(0) multiples = ([x for x in range(num + 1, num_lst[-1] + 1) if x % num == 0]) remains = ([x for x in num_lst if x not in multiples]) acc.append(num) return helper_function(remains, acc ) return helper_function(range(2, n + 1), []) </code></pre> <p>When i ran the timing, got 826 us for the post erathostenes(1000), and 26ms for my version (!!). Surprised me it was so slow.</p> <p>Functional programming it's more fun, but looks isn't the right fit for this problem, in Python (my guess is that it would be faster in a more functional language).</p> <p>So i tried a imperative version. It looks like this:</p> <pre><code>def erathostenes_imperative(n): limit = int(math.sqrt(n)) def helper_function(flags, size): for i in range(2,limit): if flags[i] == True: j = 2*i while j &lt; size: if j % i == 0: flags[j] = False j = j + i return [x for x in range(2, n + 1) if flags[x]] return helper_function([True]*(n + 1), n) </code></pre> <p>What i did was changing the list of integers into a list of True/False flags. Intuitively, looks like it's faster to iterate, right?</p> <p>My results where 831ms for erathostenes_imperative(100000), vs. 1.45 in your version.</p> <p>It's a shame that imperative writting it's faster. The code look so messy with all the fors, whiles, i's and j's</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.
    2. 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