Need help in Understanding Solution of MAGICMED

Below given is a 100 score solution. But I am unable to understand why he is passing m (no. of countries ) in power function for taking modulo. Please help.
Solution

please anybody help

in this problem basically we have to find :
Answer : (((((A ^ B) mod M) ^ C) mod M) * P) % 100000007.
ln the code above he have some checks first.

  1. if (A == 0): answer is going to be zero is this case
  2. if (A == 1): answer is going to be always (1 * (P mod 100000007))

if above are not true.
he is calculating answer.
as A and B and C can be as large as 2 * 10^7.
so we can not simply use normal power function form math.h
as integer will go out of bounds while calculation.

here comes the concept of modular exponentiation. in case you are new to this.

1 Like

Ok bro i got it.Thanks again. We are passing m because of property of modular operation.
(A^B^C)%m==((A^B)%m)^C)%m. right?

1 Like

because we are only intersted in amount of medicines that are going to be left out.

assume this you have 7 medecines, and you have to divide it equally among :

  1. case 1: 2 countries, so you will donate 3 each (which is maximal possible) and would be left with 1.
  2. case 2: 5 countries, so you will donate 1 each (which is maximal possible) and would be left with 2.

did you noticed the pattern here. amount of left outs is (total medecines mod no. of countries) .

1 Like