Check if N can be represented as sum of distinct powers of 3 | Function to try all permutations of distinct powers ; Base Case ; If the distinct powers sum is obtained ; Otherwise ; If current element not selected in power [ ] ; If current element selected in power [ ] ; Return 1 if any permutation found ; Function to check the N can be represented as the sum of the distinct powers of 3 ; Stores the all distincts powers of three to [ 0 , 15 ] ; Function Call ; print ; Driven Code
function PermuteAndFind ( power , idx , SumSoFar , target ) { if ( idx == power . length ) { if ( SumSoFar == target ) return true ; return false ; } let select = PermuteAndFind ( power , idx + 1 , SumSoFar , target ) ; let notselect = PermuteAndFind ( power , idx + 1 , SumSoFar + power [ idx ] , target ) ; return select || notselect ; } function DistinctPowersOf3 ( N ) { let power = new Array ( 16 ) ; power [ 0 ] = 1 ; for ( let i = 1 ; i < 16 ; i ++ ) power [ i ] = 3 * power [ i - 1 ] ; let found = PermuteAndFind ( power , 0 , 0 , N ) ; if ( found == true ) { document . write ( " " ) ; } else { document . write ( " " ) ; } } let N = 91 ; DistinctPowersOf3 ( N ) ;