Topics

You are given four integers: , and . is a prime number. Find . Note that . Example:

Idea

The edge cases which we need to take care of are as follows

  1. If i.e., and , then answer is .
  2. If and , then answer is 0.
  3. If and , and is divisible by , then answer is .
  4. If and , and is not divisible by , then we need to use fermat’s little theorem which states that , if is prime.

Let , which means that which simplifies to modulo , due to fermat’s little theorem application on the first part.

Thus, find and then find . These can solved using binary exponentiation (recursive or iterative versions).

Time Complexity per test case:

Code

ll binpow(ll a, ll b, ll mod) {
  if (b == 0)
    return 1;
  if (b == 1)
    return a % mod;
  ll temp = binpow(a, b >> 1, mod);
  ll tres = (temp * temp) % mod;
  if (b & 1)
    tres = (tres * a) % mod;
  return tres;
}
 
void solve() {
  ll a, b, c, p;
 
  cin >> a >> b >> c >> p;
 
  if (a % p == 0) {
    if (b == 0 and c != 0)
      cout << 1 << endl;
    else
      cout << 0 << endl;
    return;
  }
  if (a == 0 and b != 0) {
    cout << 0 << endl;
    return;
  }
  ll tres = binpow(b, c, p - 1);
  ll res = binpow(a, tres, p);
  cout << res << endl;
}