I am writing a code to calculate $P^Q$ where $P$, $Q$ are positive integers which can have number of digits up to $100000$.
I want the result as $r = P^Q \pmod{10^9+7}$, where $10^9+7$ is a prime number.
Example:
$$\begin{align} P &= 34534985349875439875439875349875\\ Q &= 93475349759384754395743975349573495 \\\quad\\ r &= 735851262 \end{align}$$
I tried using the trick:
$$\begin{align} P^Q \pmod{10^9+7} &= \underbrace{P \times P \times \ldots \times P}_{Q \text{ times}} \pmod{10^9+7} = \\ &= \Big(\underbrace{P \pmod{10^9+7} \times \ldots \times P \pmod{10^9+7}}_{Q \text{ times}}\Big) \pmod{10^9+7} \end{align}$$
Since both $P$ and $Q$ are very large, I should store them in an array and do modulo digit by digit.
Is there any efficient way of doing this or some number theory algorithm which I am missing?
Thanks in advance