RedOchre’s Python Methods
isPrime
import math
def isPrime(num):
if type(num) != int: return False
if num == 2: return True
if num < 2 or num % 2 == 0: return False
return not any(num % i == 0 for i in range(3, int(math.sqrt(num))+1, 2))
prime_factors
returns a list of all prime factors of the given number
e.g. prime_factors[12] gives [2, 2, 3]
def prime_factors(num):
if num == 1: return[num]
powers = []
limit = (num/2)+1
i = 2
if isPrime(num): return [num]
while i <= limit:
while num % i == 0:
powers.append(i)
num = num/i
i += 1
if num == 1: break
return powers

Peter Sutton said,
22 June, 2008 at 2:10 am
For speed you are better of with
def isPrime(n):
return not any(not n%i for i in xrange(3,int(sqrt(n))+1,2)) if n%2 and n>2 else False