Python Program to Check If Two Numbers are Amicable Numbers

PythonServer Side ProgrammingProgramming

Amicable numbers are two different numbers so related that the sum of the proper divisors of each is equal to the other number. When it is required to check if two numbers are amicable numbers, a method can be defined that iterates over the number, and uses the modulus operator. Another method is defined that calls the previously defined function to determine if two numbers are amicable or not.

Below is the demonstration of the same −


 Live Demo

import math

def divided_sum_val(my_val) :

   res = 0
   for i in range(2, int(math.sqrt(my_val)) + 1) :

      if (my_val % i == 0) :

         if (i == int(my_val / i)) :
            res = res + i
         else :
            res = res + (i + int(my_val / i))
   return (res + 1)

def check_amicable(x, y) :

   if (divided_sum_val(x) != y) :
      return False

   return (divided_sum_val(y) == x)

first_num = 220
second_num = 288
print("The numbers are :")
if (check_amicable(first_num, second_num)) :
   print ("The given numbers are amicable in nature")
else :
   print ("The given numbers are not amicable in nature")


The numbers are :
The given numbers are not amicable in nature


  • A method named ‘divided_sum_val’ is defined that takes an integer has parameter.

  • It uses a ‘for’ loop to iterate through the value and checks the divisibility of the number.

  • If the iterator is equal to the value divided by the iterator, it is incremented by the iterator.

  • Otherwise, the entire divided number is added.

  • Another method named ‘check_amicable’ is defined, that takes two numbers.

  • It calls the ‘divided_sum_val’ and returns ‘True’ or ‘False’ depending on the computed value.

  • The two numbers are defined, and are displayed on the console.

  • The method is called by passing these two numbers.

  • Based on the output, relevant message is displayed on the console.

Published on 19-Apr-2021 14:20:59