Check if any permutation of N equals any power of K | Java implementation of above approach . ; 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
import java . util . * ; class GfG { static boolean isValid ( int N , int K ) { HashSet < Integer > m1 = new HashSet < Integer > ( ) ; HashSet < Integer > m2 = new HashSet < Integer > ( ) ; while ( N > 0 ) { m1 . add ( N % 10 ) ; N /= 10 ; } while ( K > 0 ) { m2 . add ( K % 10 ) ; K /= 10 ; } if ( m1 . equals ( m2 ) ) { return true ; } return false ; } static String anyPermutation ( int N , int K ) { int powK [ ] = new int [ 100 + 1 ] , Limit = ( int ) Math . pow ( 10 , 18 ) ; powK [ 0 ] = K ; int i = 1 ; while ( powK [ i - 1 ] * K < Limit && i < 100 ) { powK [ i ] = powK [ i - 1 ] * K ; i ++ ; } for ( int j = 0 ; j < i ; j ++ ) { if ( isValid ( N , powK [ j ] ) ) { return " True " ; } } return " False " ; } public static void main ( String [ ] args ) { int N = ( int ) 96889010407L , K = 7 ; System . out . println ( anyPermutation ( N , K ) ) ; } }