Computer >> Computer tutorials >  >> Programming >> Python

How to check if two numbers (m,n) are amicable or not using Python?


Amicable numbers are two different numbers so related that the sum of the proper divisors of each is equal to the other number. (A proper divisor of a number is a positive factor of that number other than the number itself. For example, the proper divisors of 6 are 1, 2, and 3.)

In python, you can find these numbers by taking the sum of each of these and comparing them with the other. For example, 

def are_amicable(x, y)
   if x==y:
      return False
   # Find sum of their proper divisors
   sum_x = sum(e for e in range(1, x//2+1) if x % e == 0)
   sum_y = sum(e for e in range(1, y//2+1) if y % e == 0)
   
   #Return true of they satisfy the last condition
   return sum_x==y and sum_y==x
print(are_amicable(15, 20))
print(are_amicable(220, 284))

This will give the output

False
True