reset password
Author Message
rabbott
Posts: 1649
Posted 11:54 Jan 25, 2019 |

On Wednesday we talked about a Python program to generate primes. I suggested variants that might or might not work. The following puts a number of variants together and tries them all.

from itertools import count

def primes(i):
    primes_cache = []
    yield 2
    for k in count(3, 2):
        no_divisors = not any(p for p in primes_cache if k % p == 0)      if i == 0 else \
                      not [p for p in primes_cache if k % p == 0]         if i == 1 else \
                      all(p for p in primes_cache if k % p != 0)          if i == 2 else \
                      all(k % p != 0 for p in primes_cache)               if i == 3 else \
                      (k % p != 0 for p in primes_cache)                # if i == 4
        if no_divisors:
            primes_cache.append(k)
            yield k

for i in range(5):
    print(i, [p for (_, p) in zip(range(12), primes(i))])

When run, the result looks like this.

0 [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37]
1 [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37]
2 [2, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23]
3 [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37]
4 [2, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23]

 

Variants 0, 1, and 3 get the right answer. Variants 2 and 4 get the wrong answer.

Here are some questions.

1. How, if at all, do variants 0 and 1 differ in what they compute?

2. Variants 0 and 2 look like they are logically equivalent. But they get different answers. Why?

3. Variants 2 and 3 look very similar, but 2 gets the wrong answer and 3 gets the right answer. Why?

4. Variant 4 gets the wrong answer.  What is computed when variant 4 is run?

 

 

Last edited by rabbott at 12:01 Jan 25, 2019.