Sum of all subsets whose sum is a Perfect Number from a given array | 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
def isPerfect ( x ) : NEW_LINE INDENT sum_div = 1 NEW_LINE for i in range ( 2 , int ( x / 2 + 1 ) ) : NEW_LINE INDENT if ( x % i == 0 ) : NEW_LINE INDENT sum_div = sum_div + i NEW_LINE DEDENT DEDENT if ( sum_div == x ) : NEW_LINE INDENT return 1 NEW_LINE DEDENT else : NEW_LINE INDENT return 0 NEW_LINE DEDENT DEDENT def subsetSum ( arr , n ) : NEW_LINE INDENT total = 1 << n NEW_LINE for i in range ( total ) : NEW_LINE INDENT sum = 0 NEW_LINE for j in range ( n ) : NEW_LINE INDENT if ( i & ( 1 << j ) != 0 ) : NEW_LINE INDENT sum = sum + arr [ j ] NEW_LINE DEDENT DEDENT if ( isPerfect ( sum ) ) : NEW_LINE INDENT print ( sum , " ▁ " ) NEW_LINE DEDENT DEDENT DEDENT arr = [ 5 , 4 , 6 ] NEW_LINE N = len ( arr ) NEW_LINE subsetSum ( arr , N ) NEW_LINE