Print all the combinations of N elements by changing sign such that their sum is divisible by M | Function to print all the combinations ; Iterate for all combinations ; Initially 100 in binary if n is 3 as 1 << ( 3 - 1 ) = 100 in binary ; Iterate in the array and assign signs to the array elements ; If the j - th bit from left is set take ' + ' sign ; Right shift to check if jth bit is set or not ; Re - initialize ; Iterate in the array elements ; If the jth from left is set ; Right shift ; Driver code
function printCombinations ( a , n , m ) { for ( let i = 0 ; i < ( 1 << n ) ; i ++ ) { let sum = 0 ; let num = 1 << ( n - 1 ) ; for ( let j = 0 ; j < n ; j ++ ) { if ( ( i & num ) > 0 ) sum += a [ j ] ; else sum += ( - 1 * a [ j ] ) ; num = num >> 1 ; } if ( sum % m == 0 ) { num = 1 << ( n - 1 ) ; for ( let j = 0 ; j < n ; j ++ ) { if ( ( i & num ) > 0 ) document . write ( " " + a [ j ] + " " ) ; else document . write ( " " + a [ j ] + " " ) ; num = num >> 1 ; } document . write ( " " ) ; } } } let a = [ 3 , 5 , 6 , 8 ] ; let n = a . length ; let m = 5 ; printCombinations ( a , n , m ) ;