# Arup Guha
# 10/15/2024
# Fast Mod Expo also showing students how to format the code
# for the program on Homework 5.

# Calculates b raised to the power e modulo n.
def myfastmodexpo(b,e,n):

    # Base case.
    if e == 0:
        return 1

    # Get time savings here by going halfway and squaring.
    if e%2 == 0:
        tmp = myfastmodexpo(b,e//2,n)
        return (tmp*tmp)%n

    # Regular recursive breakdown.
    return (b*myfastmodexpo(b,e-1,n))%n


def main():

    # Read from standard input, number of cases.
    nC = int(input())

    # Go through each case.
    for loop in range(nC):

        # Get the input as a list of strings.
        toks = input().split()
        b = int(toks[0])
        e = int(toks[1])
        n = int(toks[2])

        # Call function output result.
        print(myfastmodexpo(b,e,n))

# Run it!
main()
