Sum of all subsets whose sum is a Perfect Number from a given array | Java program for the above approach ; Function to check is a given number is a perfect number or not ; Stores the sum of its divisors ; Add all divisors of x to sum_div ; If the sum of divisors is equal to the given number , return true ; Otherwise , return false ; Function to find sum of all subsets from an array whose sum is a perfect number ; Print the current subset sum if it is a perfect number ; Check if sum is a perfect number or not ; Calculate sum of the subset including arr [ l ] ; Calculate sum of the subset excluding arr [ l ] ; Driver code
import java . io . * ; import java . util . * ; class GFG { static int isPerfect ( int x ) { int sum_div = 1 ; for ( int i = 2 ; i <= x / 2 ; ++ i ) { if ( x % i == 0 ) { sum_div += i ; } } if ( sum_div == x ) { return 1 ; } else return 0 ; } static void subsetSum ( int [ ] arr , int l , int r , int sum ) { if ( l > r ) { if ( isPerfect ( sum ) != 0 ) { System . out . print ( sum + " ▁ " ) ; } return ; } subsetSum ( arr , l + 1 , r , sum + arr [ l ] ) ; subsetSum ( arr , l + 1 , r , sum ) ; } public static void main ( String [ ] args ) { int [ ] arr = { 5 , 4 , 6 } ; int N = arr . length ; subsetSum ( arr , 0 , N - 1 , 0 ) ; } }