mirror of
https://bitbucket.org/Mattrixwv/pyclasses.git
synced 2025-12-06 18:33:58 -05:00
Added an algorithm that returns a certain number of prime numbers
This commit is contained in:
@@ -35,6 +35,44 @@ def getPrimes(goalNumber: int):
|
|||||||
primes.sort()
|
primes.sort()
|
||||||
return primes
|
return primes
|
||||||
|
|
||||||
|
#This function gets a certain number of primes
|
||||||
|
def getNumPrimes(numberOfPrimes: int):
|
||||||
|
primes = []
|
||||||
|
foundFactor = False
|
||||||
|
|
||||||
|
#If the number is 0 or negative return an empty list
|
||||||
|
if(numberOfPrimes < 1):
|
||||||
|
return primes
|
||||||
|
#Otherwise there is at lease 1, meaning 2 will be the first entry
|
||||||
|
else:
|
||||||
|
primes.append(2)
|
||||||
|
|
||||||
|
#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:
|
||||||
|
#If you find a factor the number is not a prime so raise the flag and break the loop
|
||||||
|
if((possiblePrime % primeNum) == 0):
|
||||||
|
foundFactor = True
|
||||||
|
break
|
||||||
|
|
||||||
|
#If you don't find a factor then this number is prime so add it to the list
|
||||||
|
if(not foundFactor):
|
||||||
|
primes.append(possiblePrime)
|
||||||
|
#If it wasn't prime simply reset the flag
|
||||||
|
else:
|
||||||
|
foundFactor = False
|
||||||
|
#Increment to the next possible prime number
|
||||||
|
possiblePrime += 2
|
||||||
|
|
||||||
|
#Everything should already be in order, but sort it just in case
|
||||||
|
primes.sort()
|
||||||
|
|
||||||
|
#Return the list with all the prime numbers
|
||||||
|
return primes
|
||||||
|
|
||||||
|
|
||||||
#This is a function that returns all the factors of goalNumber
|
#This is a function that returns all the factors of goalNumber
|
||||||
def getFactors(goalNumber: int):
|
def getFactors(goalNumber: int):
|
||||||
#You need to get all the primes up to this number
|
#You need to get all the primes up to this number
|
||||||
|
|||||||
Reference in New Issue
Block a user