Check if any permutation of N equals any power of K | function to check if N and K are anagrams ; Function to check if any permutation of N exist such that it is some power of K ; generate all power of K under 10 ^ 18 ; check if any power of K is valid ; Driver code ; function call to print required answer
function isValid ( N , K ) { let m1 = new Set ( ) ; let m2 = new Set ( ) ; while ( N > 0 ) { m1 . add ( N % 10 ) ; N = Math . floor ( N / 10 ) ; } while ( K > 0 ) { m2 . add ( K % 10 ) ; K = Math . floor ( K / 10 ) ; } let s = new Set ( [ ... m1 , ... m2 ] ) return s . size == m1 . size && s . size == m2 . size } function anyPermutation ( N , K ) { let powK = new Array ( 100 + 1 ) , Limit = ( Math . pow ( 10 , 18 ) ) ; for ( let i = 0 ; i < 101 ; i ++ ) powK [ i ] = 0 ; powK [ 0 ] = K ; let i = 1 ; while ( powK [ i - 1 ] * K < Limit ) { powK [ i ] = powK [ i - 1 ] * K ; i ++ ; } for ( let j = 0 ; j < i ; j ++ ) { if ( isValid ( N , powK [ j ] ) ) { return " " ; } } return " " ; } let N = 96889010407 , K = 7 ; document . write ( anyPermutation ( N , K ) ) ;