Sum of all perfect numbers present in an array | Java implementation of the above approach ; Function to return the sum of all the proper factors of n ; f is the factor of n ; Function to return the required sum ; To store the sum ; If current element is non - zero and equal to the sum of proper factors of itself ; Driver code
class GFG { static int sumOfFactors ( int n ) { int sum = 0 ; for ( int f = 1 ; f <= n / 2 ; f ++ ) { if ( n % f == 0 ) { sum += f ; } } return sum ; } static int getSum ( int [ ] arr , int n ) { int sum = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( arr [ i ] > 0 && arr [ i ] == sumOfFactors ( arr [ i ] ) ) { sum += arr [ i ] ; } } return sum ; } public static void main ( String [ ] args ) { int [ ] arr = { 17 , 6 , 10 , 6 , 4 } ; int n = arr . length ; System . out . print ( getSum ( arr , n ) ) ; } }