Created
May 11, 2017 20:20
-
-
Save TApicella/f089a87c11b822fcaf7fe23141bdd4d7 to your computer and use it in GitHub Desktop.
RosettaCode- Count in factors created by tapicella - https://repl.it/Hthb/12
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
''' | |
http://rosettacode.org/wiki/Count_in_factors | |
Write a program which counts up from 1, displaying each number as the multiplication of its prime factors. | |
For the purpose of this task, 1 (unity) may be shown as itself. | |
Example | |
2 is prime, so it would be shown as itself. | |
6 is not prime; it would be shown as 2 × 3 | |
2144 is not prime; it would be shown as 2 × 2 × 2 × 2 × 2 × 67 | |
''' | |
#Note- I am going to try my own approach to get prime factors rather than looking something up | |
prime_array = [0, 1, 2, 3] #This should allow me to optimize by testing division against primes once they are found | |
def getFactors(num): | |
max_factor = num | |
if num in prime_array: | |
return [num] | |
else: | |
for i in range(2, len(prime_array)): #skip zero and one | |
prime = prime_array[i] | |
if num%prime == 0: | |
return [prime]+getFactors(num//prime) | |
#If dividing by a prime doesn't work, start iterating manually | |
j = prime+1 | |
#max_factor will be num//j. Example: for 121, we wouldn't need to check 12 because 121//10 = 12, so 12 times anything greater will be more than 121 | |
while j < max_factor: | |
if num%j == 0: | |
return getFactors(j)+getFactors(num//j) | |
else: | |
max_factor = num//j | |
j = j+1 | |
#if j hits max factor without being a factor, we know that num is prime | |
prime_array.append(num) | |
prime_array.sort() | |
return [num] | |
for x in range(50): | |
str_factors = list(map(str, getFactors(x))) | |
print("Factorized %s: %s" % (str(x),' x '.join(str_factors))) | |
print(getFactors(2144)) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment