November 3, 2017
Amicable numbers in Python
Definition
Please refer to the following article for definition. This article reimplements it in Python.
Code
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 |
def isAmicable(n, m): # Sum of (n) proper divisors ns = 0 # Sum of (m) proper divisors ms = 0 # Boolean: 1 if the sum of (n) proper divisors equals to (m) nb = 0 # Boolean: 1 if the sum of (m) proper divisors equals to (n) mb = 0 # Find all proper divisors of (n) and calculate the sum for i in range(1, n): if n % i == 0: ns = ns + i # This must be true if the pair are amicable if ns == m: nb = 1 # Find all proper divisors of (m) and calculate the sum for j in range(1, m): if m % j == 0: ms = ms + j # This must be true if the pair are amicable if ms == n: mb = 1 # If both conditions are true then (n) and (m) are amicable if nb == 1 and mb == 1: return 1 else: return 0 # Sample numbers n = 5020 m = 5564 # Check if they are amicable if isAmicable(n, m) == 1: print "YES" else: print "NO" |