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 sum of 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 the sum of all the subsets from an array whose sum is a perfect number ; Stores the total number of subsets , i . e . 2 ^ n ; Consider all numbers from 0 to 2 ^ n - 1 ; Consider array elements from positions of set bits in the binary representation of n ; If sum of chosen elements is a perfect number ; Driver Code
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 n ) { long total = 1 << n ; for ( long i = 0 ; i < total ; i ++ ) { int sum = 0 ; for ( int j = 0 ; j < n ; j ++ ) if ( ( i & ( 1 << j ) ) != 0 ) sum += arr [ j ] ; if ( isPerfect ( sum ) != 0 ) { System . out . print ( sum + " ▁ " ) ; } } } public static void main ( String [ ] args ) { int arr [ ] = { 5 , 4 , 6 } ; int N = arr . length ; subsetSum ( arr , N ) ; } }