Pairs of Amicable Numbers | Efficient Java 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
import java . util . * ; 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 < Integer > s = new HashSet < Integer > ( ) ; 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 ; System . out . println ( countPairs ( arr1 , n1 ) ) ; int arr2 [ ] = { 2620 , 2924 , 5020 , 5564 , 6232 , 6368 } ; int n2 = arr2 . length ; System . out . println ( countPairs ( arr2 , n2 ) ) ; } }