Help needed in a Modular arithmetic question

def mysterious_function(A,B):
    for number in A:
        ans=power(number,ans) // power(number,ans) returns number raised to power ans
    return ans%B

We have to evaluate the above function for array A and an integer B. Values in the array and the integer B is around 40,000.

What I thought is to break B in primes and then use CRT to merge the result but I got stuck thinking that what to do if we have a power of primes. Like when B is 12 or something which includes a prime more than once. Because I thought of using Fermat Little theorem if modulus is prime.

Can someone guide me in solving the problem?