Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the most efficient way to find amicable numbers in python?

I've written code in Python to calculate sum of amicable numbers below 10000:

def amicable(a, b):
   total = 0
   result = 0
   for i in range(1, a):
      if a % i == 0:
        total += i
   for j in range(1, b):
      if b % j == 0:
        result += j
   if total == b and result == a:
        return True
   return False

sum_of_amicables = 0
for m in range (1, 10001):
    for n in range (1, 10001):
        if amicable(m, n) == True and m != n:
            sum_of_amicables = sum_of_amicables + m + n

Code is running more than 20 minutes in Python 2.7.11. Is it ok? How can I improve it?

like image 521
Fadai Mammadov Avatar asked Oct 14 '25 07:10

Fadai Mammadov


1 Answers

optimized to O(n)

def sum_factors(n):  
     result = []
     for i in xrange(1, int(n**0.5) + 1):
         if n % i == 0:
             result.extend([i, n//i])
     return sum(set(result)-set([n]))

def amicable_pair(number):
    result = []
    for x in xrange(1,number+1):
        y = sum_factors(x)
        if sum_factors(y) == x and 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 only 0.2 seconds on macbook pro

like image 179
Yuan Bonan Avatar answered Oct 17 '25 07:10

Yuan Bonan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!