diff --git a/Algorithms.py b/Algorithms.py index 06a3f59..eafda45 100644 --- a/Algorithms.py +++ b/Algorithms.py @@ -1,7 +1,7 @@ #Python/myClasses/Algorithms.py #Matthew Ellison # Created: 1-27-19 -#Modified: 1-29-19 +#Modified: 1-30-19 #This is a file that contains a few algorithms that I have used several times import math @@ -20,11 +20,19 @@ def getPrimes(goalNumber: int): 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 - #See if the current possible prime is divisible by any prime less than it. If not it is a prime itself - for primeNum in primes: - if((possiblePrime % primeNum) == 0): + #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): @@ -50,12 +58,20 @@ def getNumPrimes(numberOfPrimes: int): #Loop through every odd number starting at 3 until you reach the correct number of entries looking for a prime number possiblePrime = 3 #Holds the next possible prime number while((len(primes) < numberOfPrimes) and (possiblePrime > 0)): - #Loop through all primes we have already found, checking for a factor - for primeNum in primes: + #Loop through all primes we have already found, up to sqrt(possiblePrime), checking for a factor + 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 you find a factor the number is not a prime so raise the flag and break the loop - if((possiblePrime % primeNum) == 0): + if((possiblePrime % primes[primesCnt]) == 0): foundFactor = True break + else: + primesCnt += 1 + #Check if the index has gone out of bounds and break the loop if it has + if(primesCnt >= len(primes)): + break #If you don't find a factor then this number is prime so add it to the list if(not foundFactor):