Amicable numbers in Python

amicable

Definition

Please refer to the following article for definition. This article reimplements it in Python.

Code

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"
Tags:

Leave a Reply