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
< ? php function printCombinations ( $ a , $ n , $ m ) { for ( $ i = 0 ; $ i < ( 1 << $ n ) ; $ i ++ ) { $ sum = 0 ; $ num = 1 << ( $ n - 1 ) ; for ( $ j = 0 ; $ j < $ n ; $ j ++ ) { if ( $ i & $ num ) $ sum += $ a [ $ j ] ; else $ sum += ( -1 * $ a [ $ j ] ) ; $ num = $ num >> 1 ; } if ( $ sum % $ m == 0 ) { $ num = 1 << ( $ n - 1 ) ; for ( $ j = 0 ; $ j < $ n ; $ j ++ ) { if ( ( $ i & $ num ) ) echo " + " ▁ , ▁ $ a [ $ j ] ▁ , ▁ " " ; STRNEWLINE TABSYMBOL TABSYMBOL TABSYMBOL TABSYMBOL else STRNEWLINE TABSYMBOL TABSYMBOL TABSYMBOL TABSYMBOL TABSYMBOL echo ▁ " - " ▁ , ▁ $ a [ $ j ] ▁ , ▁ " " $ num = $ num >> 1 ; } echo " STRNEWLINE " ; } } } $ a = array ( 3 , 5 , 6 , 8 ) ; $ n = sizeof ( $ a ) ; $ m = 5 ; printCombinations ( $ a , $ n , $ m ) ; ? >