Fixed get prime functions

This commit is contained in:
2020-10-29 11:05:28 -04:00
parent 0b31ecd522
commit da0ae679b7

View File

@@ -62,46 +62,34 @@ def fibGenerator():
#This function returns a list with all the prime numbers <= goalNumber
def getPrimes(goalNumber: int) -> list:
primes = []
foundFactor = False
gen = primeGenerator() #The prime number generator
primes = [] #The list of prime numbers
#If the number is 0 or negative return an empty list
#If the number is <= 1 return a blank list
#?Should this throw an exception if goalNumber < 0
if(goalNumber <= 1):
return primes
#Otherwise the number is at least 2, therefore 2 should be added to the list
else:
primes.append(2)
#We can now start at 3 and skip all even numbers, because they cannot be prime
for possiblePrime in range(3, goalNumber + 1, 2): #Need goalNumber + 1 to account for goalNumber being prime
#Check all current primes, up to sqrt(possiblePrime), to see if there is a divisor
primesCnt = 0
#We can safely assume that there will at lease be 1 element in the primes list because of 2 being added before the loop
topPossibleFactor = math.ceil(math.sqrt(possiblePrime))
while(primes[primesCnt] <= topPossibleFactor):
if((possiblePrime % primes[primesCnt]) == 0):
foundFactor = True
break
else:
primesCnt += 1
#Check if the index has gone out of range
if(primesCnt >= len(primes)):
break
#If you didn't find a factor then the current number must be prime
if(not foundFactor):
primes.append(possiblePrime)
else:
foundFactor = False
#There is at least 1 prime number
primes.append(next(gen))
#Loop until you find all the prime numbers requested
while(primes[len(primes) - 1] < goalNumber):
primes.append(next(gen))
primes.sort()
return primes
#This function gets a certain number of primes
def getNumPrimes(numberOfPrimes: int) -> list:
gen = primeGenerator()
#gen = postponed_sieve()
primes = []
gen = primeGenerator() #The prime number generator
primes = [] #The list of prime numbers
#If the number is < 1 return a blank list
#?Should this throw an exception if numberOfPrimes < 0
if(numberOfPrimes < 1):
return primes
#Count how many primes you are adding to the list and stop when you reach the requested length
for _ in range(1, numberOfPrimes + 1):
primes.append(next(gen))