Pairs of Amicable Numbers | Efficient C # program to count Amicable pairs in an array . ; Calculate the sum of proper divisors ; 1 is a proper divisor ; To handle perfect squares ; Check if pair is amicable ; 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
using System ; using System . Collections . Generic ; class GFG { static int sumOfDiv ( int x ) { int sum = 1 ; for ( int i = 2 ; i <= Math . Sqrt ( x ) ; i ++ ) { if ( x % i == 0 ) { sum += i ; if ( x / i != i ) sum += x / i ; } } return sum ; } static Boolean isAmicable ( int a , int b ) { return ( sumOfDiv ( a ) == b && sumOfDiv ( b ) == a ) ; } static int countPairs ( int [ ] arr , int n ) { HashSet < int > s = new HashSet < int > ( ) ; int count = 0 ; for ( int i = 0 ; i < n ; i ++ ) s . Add ( arr [ i ] ) ; for ( int i = 0 ; i < n ; i ++ ) { if ( s . Contains ( sumOfDiv ( arr [ i ] ) ) ) { int sum = sumOfDiv ( arr [ i ] ) ; if ( isAmicable ( arr [ i ] , sum ) ) count ++ ; } } return count / 2 ; } public static void Main ( String [ ] args ) { int [ ] arr1 = { 220 , 284 , 1184 , 1210 , 2 , 5 } ; int n1 = arr1 . Length ; Console . WriteLine ( countPairs ( arr1 , n1 ) ) ; int [ ] arr2 = { 2620 , 2924 , 5020 , 5564 , 6232 , 6368 } ; int n2 = arr2 . Length ; Console . WriteLine ( countPairs ( arr2 , n2 ) ) ; } }