Python program to check if two numbers are Amicable or not
Hello, In this Lecture, we are going to code a Python program to check if two numbers are Amicable numbers or not.
First of all, what is this Amicable? we say two numbers are Amicable if the sum of proper divisors is equal to the opposite numbers that are the sum of divisors of x is equal to y and sum of divisors of y is equal to x. we can understand it clearly through an example.
Let us take 234, 339 as two numbers now we should find the divisors of 123 and 456 let their sums be sum1 and sum2 respectively. Then sum2 must be equal to 123 and sum1 equal to 456.
We should find all the proper divisors of x,y and then sum then separately and then match them to the opposite numbers and if they match then we say the two numbers are Amicable else not.
sum_x=y and sum_y=x
Steps to check if two numbers are amicable in Python
- First, take two numbers as input from the user.
- Calculate the sum of proper divisors of both the numbers.
- Now check if the sums are equal to the opposite numbers.
- If they are equal then they are Amicable else not.
- Finally, print the output.
Our Python program
Below is our Python code:
x=int(input()) y=int(input()) sum_x=0 sum_y=0 for each in range(1,x): if(x%each==0): sum_x=sum_x+each for i in range(1,y): if(y%i==0): sum_y=sum_y+i if(sum_x==y and sum_y==x): print("They are Amicable numbers") else: print("No they are not Amicable")
The output of our program will be like you can see below:
220 284 They are Amicable numbers
See another output with different input values:
123 456 No, they are not Amicable
Now let’s see what we did in our code. So it’s time to see a brief explanation of our Python code that you see in this example.
- Python program to validate a credit card number
- Python program to check if two lines are parallel or not
The input() function is used to take the string input from the user that is why I converted it to int.
Now we write for loop for finding the sum of the proper divisors of the numbers and finally checking
it with the input numbers.
I hope, you have understood and enjoyed this lecture check below for more interesting programs.