Check if any permutation of N equals any power of K | CPP 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 program ; function call to print required answer
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool isValid ( long long int N , long long int K ) { multiset < int > m1 , m2 ; while ( N > 0 ) { m1 . insert ( N % 10 ) ; N /= 10 ; } while ( K > 0 ) { m2 . insert ( K % 10 ) ; K /= 10 ; } if ( m1 == m2 ) return true ; return false ; } string anyPermutation ( long long int N , long long int K ) { long long int powK [ 100 ] , Limit = pow ( 10 , 18 ) ; powK [ 0 ] = K ; int i = 1 ; while ( powK [ i - 1 ] * K < Limit ) { powK [ i ] = powK [ i - 1 ] * K ; i ++ ; } for ( int j = 0 ; j < i ; j ++ ) if ( isValid ( N , powK [ j ] ) ) { return " True " ; } return " False " ; } int main ( ) { long long int N = 96889010407 , K = 7 ; cout << anyPermutation ( N , K ) ; return 0 ; }