2
\$\begingroup\$

Below is the code for knowing all the prime factors of a number. I think there must be some better way of doing the same thing. Also, please tell me if there are some flaws in my code.

def factorize(num):
 res2 = "%s: "%num
 res = []
 while num != 1:
 for each in range(2, num + 1):
 quo, rem = divmod(num, each)
 if not rem:
 res.append(each)
 break
 num = quo
 pfs = set(res)
 for each in pfs:
 power = res.count(each)
 if power == 1:
 res2 += str(each) + " "
 else:
 res2 += str(each) + '^' + str(power) + " "
 return res2
toxotes
2752 silver badges12 bronze badges
asked Feb 2, 2013 at 13:15
\$\endgroup\$
0

1 Answer 1

6
\$\begingroup\$
def factorize(num):
 res2 = "%s: "%num

You'd be much better off to put the string stuff in a seperate function. Just have this function return the list of factors, i.e. res and have a second function take res as a parameter and return the string. That'd make your logic simpler for each function.

 res = []

Don't needlessly abbreviate. It doesn't save you any serious amount of typing time and makes it harder to follow your code.

 while num != 1:
 for each in range(2, num + 1):

To be faster here, you'll want recompute the prime factors of the numbers. You can use the Sieve of Eratosthenes. Just keep track of the prime factors found, and you'll just be able to look them up.

 quo, rem = divmod(num, each)
 if not rem:
 res.append(each)
 break
 num = quo

Your function dies here if you pass it a zero.

 pfs = set(res)

Rather than a set, use collections.Counter, it'll let you get the counts at the same time rather then recounting res.

 for each in pfs:
 power = res.count(each)
 if power == 1:
 res2 += str(each) + " "
 else:
 res2 += str(each) + '^' + str(power) + " "

String addition is inefficient. I'd suggest using "{}^{}".format(each, power). Also, store each piece in a list and then use " ".join to make them into a big string at the end.

 return res2
Quentin Pradet
7,0641 gold badge25 silver badges44 bronze badges
answered Feb 2, 2013 at 14:15
\$\endgroup\$

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.