The Sieve of Eratosthones (Again). Look at Sieve of Eratosthenes and
Sieve of Eratosthenes. We created a
list or a set of candidate prime numbers.
This exercise has three parts: initialization, generating the
list (or set) or
prime numbers, then reporting. In the list
version, we had to filter the sequence of boolean values to
determine the primes. In the set version,
the set contained the primes.
Within the Generate step, there is a
point where we know that the value of p is prime.
At this point, we can yield p. If yield each value as we discover
it, we eliminate the entire "report" step from the function.
The Generator Version of range. The range function creates a sequence. For very large
sequences, this consumes a lot of memory. You can write a version
of range which does not create the entire sequence, but instead
yields the individual values. Using a generator will have the same
effect as iterating through a sequence, but won't consume as much
Define a generator, genrange, which
generates the same sequence of values as range,
without creating a list object.
Check the documentation for the built-in function
Prime Factors. There are two kinds of positive numbers: prime numbers and
composite numbers. A composite number is the product of a sequence
of prime numbers. You can write a simple function to factor
numbers and yield each prime factor of the number.
Your factor function can accept a number,
n, for factoring. The function will test values,
f, between 2 and the square root of
n to see if the expression n % f ==
0 is true. If this is true. then the factor,
f, divides n with no
remainder; f is a factor.
Don't use a simple-looking for-loop; the
prime factor of 128 is 2, repeated 7 times.
Subroutines and Coroutines
Published under the terms of the Open Publication License