# Check if any permutation of N equals any power of K in Python

Suppose, we have two positive integers n and m, such that 2 ≤ n ≤ 1018 and 2 ≤ m ≤ n. Our goal is to find out if there are any all-digit-permutations of the number n; so that it is equal to some power of m. If there is one, we state that there exists an all-digit-permutation of n that is equal to a power of m, otherwise we state the previous statement as false.

For example, we are given n = 7182 and m = 12. As 1728 is an all-digit-permutation of 7182 and 1728 = 12^3, we state that an all-digit-permutation of n is equal to a power of m.

So, if the input is like n= 7182, m = 12; then the output will be "An all digit-permutation of n is equal to a power of m".

To solve this, we will follow these steps −

• Define a function check_power() . This will take n, m
• temp_arr_1 := a new list
• temp_arr_2 := a new list
• while n > 0, do
• insert (n mod 10) at the end of temp_arr_1
• n := floor value of n / 10
• while m > 0, do
• insert (m mod 10) at the end of temp_arr_2
• m := floor value of m / 10
• if a new set from temp_arr_1 is same as a new set from temp_arr_2, then
• return True
• return False
• From the main method do the following −
• power_array := a new list of size 100 initialized with 0s.
• max_range := 10^18
• power_array := m
• i := 1
• while (power_array[i - 1] * m) < max_range, do
• power_array[i] := power_array[i - 1] * m
• i := i + 1
• for j in range 0 to i, do
• if check_power(n, power_array[j]) is True, then
• return "An all digit-permutation of n is equal to a power of m"
• return "No all digit-permutation of n is equal to a power of m"

Let us see the following implementation to get better understanding −

## Example

Live Demo

def check_power(n, m):
temp_arr_1 = []
temp_arr_2 = []
while (n > 0) :
temp_arr_1.append(n % 10)
n //= 10
while (m > 0) :
temp_arr_2.append(m % 10)
m //= 10
if (set(temp_arr_1) == set(temp_arr_2)):
return True
return False
def solve(n, m):
power_array =  * 100
max_range = pow(10, 18)
power_array = m
i = 1
while (power_array[i - 1] * m < max_range) :
power_array[i] = power_array[i - 1] * m
i += 1
for j in range(i):
if (check_power(n, power_array[j])) :
return "An all digit-permutation of n is equal to a power of m"
return "No all digit-permutation of n is equal to a power of m"
n, m = 7182, 12
print(solve(n, m))

## Input

7182, 12

## Output

An all digit-permutation of n is equal to a power of m