Dremendo Tag Line

Input two numbers and check if they form an amicable pair or not using a function in Python

Function - Question 7

In this question, we will see how to input two numbers and check if they form an amicable pair or not in Python programming using a function. To know more about function click on the function lesson.

Q7) Write a program in Python to input two numbers and check if they form an amicable pair or not using a function. The function should return 1 if the numbers form an amicable pair else return 0.

An amicable pair is such that, the sum of the factors excluding itself of first number is equal to the second number and sum of factors excluding itself of the second number is equal to the first number. Example, (220, 284) are amicable pair since sum of factors excluding itself of first number is 284 and sum of factors excluding itself of second number is 220:

220=1+2+4+5+10+11+20+22+44+55+110=284
284=1+2+4+71+142=220

Program

def amicable(a,b):
    fs1=0   # factor sum of first number
    fs2=0   # factor sum of second number
    for i in range(1,a):
        if a%i==0:
            fs1=fs1+i

    for i in range(1,b):
        if b%i==0:
            fs2=fs2+i

    if fs1==b and fs2==a:
        return 1

    return 0


# main program
print('Enter 2 numbers')
a=int(input())
b=int(input())
if amicable(a,b)==1:
    print('Amicable Pair')
else:
    print('Not Amicable Pair')

Output

Enter 2 numbers
220
284
Amicable Pair
video-poster