What is the most efficient way to find amicable numbers in python? -
i've written code in python calculate sum of amicable numbers below 10000:
def amicable(a, b): total = 0 result = 0 in range(1, a): if % == 0: total += j in range(1, b): if b % j == 0: result += j if total == b , result == a: return true return false sum_of_amicables = 0 m in range (1, 10001): n in range (1, 10001): if amicable(m, n) == true , m != n: sum_of_amicables = sum_of_amicables + m + n
code running more 20 minutes in python 2.7.11. ok? how can improve it?
optimized o(n)
def sum_factors(n): result = [] in xrange(1, int(n**0.5) + 1): if n % == 0: result.extend([i, n//i]) return sum(set(result)-set([n])) def amicable_pair(number): result = [] x in xrange(1,number+1): y = sum_factors(x) if sum_factors(y) == x , x != y: result.append(tuple(sorted((x,y)))) return set(result)
run it
start = time.time() print (amicable_pair(10000)) print time.time()-start
result
set([(2620, 2924), (220, 284), (6232, 6368), (1184, 1210), (5020, 5564)]) 0.180204153061
takes 0.2 seconds on macbook pro
Comments
Post a Comment