Extensible prime generator: Difference between revisions

→‎{{Header|Python}}: Second seen as poor so removed in favour of adequate first solution.
(→‎{{Header|Python}}: Second seen as poor so removed in favour of adequate first solution.)
Line 554:
The 10,000th prime:
104729</pre>
 
----
 
Alternately, we can use the much simpler infinite primes generator from [[Sieve of Eratosthenes#Infinite generator]]. It doesn't have an upper limit; it has an infinite loop (<code>while True:</code>) in the generator function and will keep on generating as many as needed.
 
<lang python>from __future__ import print_function
from sieve_of_eratosthenes_infinite_generator import sieve
from itertools import islice
 
 
def p_range(lower_inclusive, upper_exclusive):
'Primes in the range'
for p in sieve():
if p >= upper_exclusive: break
if p >= lower_inclusive: yield p
 
if __name__ == '__main__':
print('The first twenty primes:\n ', list(islice(sieve(),20)))
print('The primes between 100 and 150:\n ', list(p_range(100, 150)))
print('The ''number'' of primes between 7,700 and 8,000:\n ', len(list(p_range(7700, 8000))))
print('The 10,000th prime:\n ', next(islice(sieve(),10000-1, 10000)))</lang>
 
{{out}}
<pre>The first twenty primes:
[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71]
The primes between 100 and 150:
[101, 103, 107, 109, 113, 127, 131, 137, 139, 149]
The number of primes between 7,700 and 8,000:
30
The 10,000th prime:
104729</pre>
The above works fine although slowly for Pythod 3 which has an only Integer type which is infinite precision (subject only to available memory) but only works for prime ranges above 46349 if the integers are the long (L) type which is then the same as the default integer type for Python 3. It is actually quite a poor algorithm in that it does not postpone the adding of the prime culling sequences to the Priority Queue until needed nor is the Priority Queue the best choice for large ranges in that it suffers from a log n (or log square root of n if properly postponed) instead of the linear amortized access for a hash table based dictionary.
 
For an extensible range prime generator it would be better to use one of the following implementations where the adding of culling sequences is postponed and which use the dictionary type.
 
=={{header|Racket}}==
Anonymous user