I'm trying to code a prime number finder that prints primes between two given values. I've got no problem with coding traditional sieve, but when it comes segmented, my python knowledge is coming up short. Here is what I've done so far:
def primes(n): # traditional sieve finding primes up to sqrt(n)
myPrimeList= []
mySieve= array('B', [True]) * (int(n**0.5)+1)
for i in range(2,int((n**0.5)+1)):
if mySieve[i]:
myPrimeList.append(i)
for x in range(i*i,int(n**0.5)+1,i):
mySieve[x]= False
return myPrimeList
def rangedprimes(x,y):
output = []
sieve = [True] * (y-x+1)
primeList = primes(y) # primes up to sqrt(y)
minimums = [(x//m)*m for m in primeList if x>=m] # multiplying primes so they get close to the lower limit
zipped = list(zip(primeList, minimums)) # just zipped to see it clearer, contributes nothing
return zipped
print(primes(20))
print(rangedprimes(10,20))
[2, 3] # primes up to sqrt(20)
[(2, 10), (3, 9)] # primes and their smallest multiples
Now, according to the algorithm, I have to turn these numbers' [10, 12, 14, 15, 16, 18, 20] values from True
to False
in the sieve so that the remaining numbers, which will be marked with True, can be prime numbers. At this point, I can't make that happen as I've got a sieve containing True
only y-x+1
times, which means it has indexes from 0
to y-x
. For example, how can 16 or 20 can be marked with False
in a sieve where the last index number will only be 10? If the starting index number of the sieve
were to be 10, and the last index number be 20, I could find the numbers in the sieve by looking their indexes and make them False
.
What should be the relationship between the sieve and the composite numbers between the range in this case?
1
toy
. 2. return primes betweenx
andy
. It's not clear why your "sieve" stops atsqrt(n)
. – jonrsharpesqrt(n)
is enough to find the primes betweenx,y
. For example, you don't have to decide whether 7 is prime or not if your upper limit is 20. The algorithm will cross out 14(the only multiple of 7 up to 20) because of 2. It's just an optimization thing, but my issue is, I can find the numbers that must be gone, however, I can't, because of my lack of python knowledge. – user2694307sqrt
, but the sieve array should contain all numbers up ton
.primes(20)
should give[2, 3, 5, 7, 11, 13, 17, 19]
, not just[2, 3]
. – jonrsharpeTrue
. – user2694307