mirror of
https://bitbucket.org/Mattrixwv/pyclasses.git
synced 2025-12-06 18:33:58 -05:00
64 lines
2.1 KiB
Python
64 lines
2.1 KiB
Python
#Python/myClasses/Algorithms.py
|
|
#Matthew Ellison
|
|
# Created: 1-27-19
|
|
#Modified: 1-27-19
|
|
#This is a file that contains a few algorithms that I have used several times
|
|
|
|
import math
|
|
|
|
#This function returns a list with all the prime numbers <= goalNumber
|
|
def getPrimes(goalNumber: int):
|
|
primes = []
|
|
foundFactor = False
|
|
|
|
#If the number is 0 or negative return an empty list
|
|
if(goalNumber <= 1):
|
|
return primes
|
|
|
|
#If the number is even 2 is a factor and all other factors will be odd
|
|
if((goalNumber %2) == 0):
|
|
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):
|
|
foundFactor = True
|
|
break
|
|
|
|
#If you didn't find a factor then the current number must be prime
|
|
if(not foundFactor):
|
|
primes.append(possiblePrime)
|
|
else:
|
|
foundFactor = False
|
|
|
|
primes.sort()
|
|
return primes
|
|
|
|
#This is a function that returns all the factors of goalNumber
|
|
def getFactors(goalNumber: int):
|
|
#You need to get all the primes up to this number
|
|
primes = getPrimes(math.ceil(math.sqrt(goalNumber))) #If there is a prime it must be <= sqrt(num)
|
|
factors = []
|
|
|
|
#If you didn't get any primes the number itself must be a prime
|
|
factors.append(goalNumber)
|
|
#You need to step through each prime and see if it is a factor in the number
|
|
cnt = 0
|
|
while((cnt < len(primes)) and (goalNumber > 1)):
|
|
#If the prime is a factor you need to add it to the factor list
|
|
if((goalNumber % primes[cnt]) == 0):
|
|
factors.append(primes[cnt])
|
|
goalNumber /= primes[cnt]
|
|
#Otherwise advance the location in primes you are looking at
|
|
#By not advancing if the prime is a factor you allow for multiple of the same prime number as a factor
|
|
else:
|
|
cnt += 1
|
|
|
|
#If for some reason the goalNumber is not 0 print an error message
|
|
if(goalNumber > 1):
|
|
print("There was an error in getFactors(). A leftover of " + str(goalNumber))
|
|
|
|
#Return the list of factors
|
|
return factors
|