Pairs of Amicable Numbers | Calculate the sum of proper divisors ; 1 is a proper divisor ; To handle perfect squares ; Check if pair is amicable ; This function prlets 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
function sumOfDiv ( x ) { let sum = 1 ; for ( let i = 2 ; i <= Math . sqrt ( x ) ; i ++ ) { if ( x % i == 0 ) { sum += i ; if ( x / i != i ) sum += x / i ; } } return sum ; } function isAmicable ( a , b ) { return ( sumOfDiv ( a ) == b && sumOfDiv ( b ) == a ) ; } function countPairs ( arr , n ) { let s = new Set ( ) ; let count = 0 ; for ( let i = 0 ; i < n ; i ++ ) s . add ( arr [ i ] ) ; for ( let i = 0 ; i < n ; i ++ ) { if ( s . has ( sumOfDiv ( arr [ i ] ) ) ) { let sum = sumOfDiv ( arr [ i ] ) ; if ( isAmicable ( arr [ i ] , sum ) ) count ++ ; } } return Math . floor ( count / 2 ) ; } let arr1 = [ 220 , 284 , 1184 , 1210 , 2 , 5 ] ; let n1 = arr1 . length ; document . write ( countPairs ( arr1 , n1 ) + " " ) ; let arr2 = [ 2620 , 2924 , 5020 , 5564 , 6232 , 6368 ] ; let n2 = arr2 . length ; document . write ( countPairs ( arr2 , n2 ) + " " ) ;