Pairs of Amicable Numbers | Efficient Python3 program to count Amicable pairs in an array . ; Calculating the sum of proper divisors ; 1 is a proper divisor ; To handle perfect squares ; check if pair is ambicle ; This function prints count of amicable pairs present in the input array ; Map to store the numbers ; Iterate through each number , and find the sum of proper divisors and check if it 's  also present in the array ; It 's sum of proper divisors ; As the pairs are counted twice , thus divide by 2 ; Driver Code
import math NEW_LINE def sumOfDiv ( x ) : NEW_LINE INDENT sum = 1 ; NEW_LINE for i in range ( 2 , int ( math . sqrt ( x ) ) ) : NEW_LINE INDENT if x % i == 0 : NEW_LINE INDENT sum += i NEW_LINE if i != x / i : NEW_LINE INDENT sum += x / i NEW_LINE DEDENT DEDENT DEDENT return int ( sum ) ; NEW_LINE DEDENT def isAmbicle ( a , b ) : NEW_LINE INDENT return ( sumOfDiv ( a ) == b and sumOfDiv ( b ) == a ) NEW_LINE DEDENT def countPairs ( arr , n ) : NEW_LINE INDENT s = set ( ) NEW_LINE count = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT s . add ( arr [ i ] ) NEW_LINE DEDENT for i in range ( n ) : NEW_LINE INDENT if sumOfDiv ( arr [ i ] ) in s : NEW_LINE INDENT sum = sumOfDiv ( arr [ i ] ) NEW_LINE if isAmbicle ( arr [ i ] , sum ) : NEW_LINE INDENT count += 1 NEW_LINE DEDENT DEDENT DEDENT return int ( count / 2 ) ; NEW_LINE DEDENT arr1 = [ 220 , 284 , 1184 , 1210 , 2 , 5 ] NEW_LINE n1 = len ( arr1 ) NEW_LINE print ( countPairs ( arr1 , n1 ) ) NEW_LINE arr2 = [ 2620 , 2924 , 5020 , 5564 , 6232 , 6368 ] NEW_LINE n2 = len ( arr2 ) NEW_LINE print ( countPairs ( arr2 , n2 ) ) NEW_LINE