Find remainder when a number A raised to N factorial is divided by P

Given three integers A, N and P, the task is to find (A^(N!)) % P.Examples:Input: A = 2, N = 1, P = 2Output: 0Explanation: As (2^(1!)) = 2Therefore 2 % 2 will be 0.Input: A = 3, N = 3, P = 2Output: 1Naive Approach: The simplest solution of this problem can be find out factorial of N say f, and now calculate A to power f say pow and find its remainder with P.Below is the implementation of the above approach:C++#include   using namespace std;  long long int fact(long long int n){    long long int ans = 1;          for (long long int i = 2; i