patternpythonMinor
Factorisation code running slow
Viewed 0 times
factorisationcoderunningslow
Problem
I'm still in the process of learning Python and am doing some of the Project Euler problems.
I have made a factorisation algorithm that works; however, it runs really slowly, and I'm not too well-versed on coding for performance. If someone could give me some pointers on how to improve the algorithm's efficiency it would be a huge help.
I have made a factorisation algorithm that works; however, it runs really slowly, and I'm not too well-versed on coding for performance. If someone could give me some pointers on how to improve the algorithm's efficiency it would be a huge help.
def factorise(num_to_factorize):
"""This method returns a list of factors for a particular number passed in to the parameters."""
factors = []
for i in range(1,math.floor(num_to_factorize/2)+1): # Loops from 1 to half the number, floors for odd numbers.
if num_to_factorize % i == 0: # Factor check.
factors.append(i) # Append on to an array to be checked.
factors.append(num_to_factorize) # Append the number itself as it is a factor.
return factors
def prime_factorise(num_to_prime_factorize):
"""This method returns the prime factors of the number passed in to the method as a parameter."""
prime_factors = []
for factor in factorise(num_to_prime_factorize): # Loop through each factor.
if factorise(factor) == [1, factor] or factorise(factor) == [1]: # if prime factors
prime_factors.append(factor)
return prime_factorsSolution
I'll give you some hints/comments:
I don't want to give away the answer, so, hopefully these tips will suffice to get you in the right direction.
factorise(factor) == [1, factor] or factorise(factor)calculatesfactorise(factor)twice, consider saving its result as a variable and re-using it instead of incurring the cost twice.
- You're treating 1 as a special case (in
factorise(factor) == [1]), but it isn't.1can be factored into anything, but should not be considered a prime factor. Why? Because1isn't a prime.
- I think your algorithm might be slightly off. For example, if I say
prime_factorise(8)I get[1, 2], but I believe the answer should be[2, 2, 2]since 2 is prime, and 222 = 8.
- Overall, my biggest hint would be try to improve your algorithm by thinking of the operation as a reduction from some number, into its prime factors. Think _how can I transform
num_to_prime_factorizeinto a list of its prime factors ("transform" being key).
I don't want to give away the answer, so, hopefully these tips will suffice to get you in the right direction.
Context
StackExchange Code Review Q#80428, answer score: 3
Revisions (0)
No revisions yet.