Modular mathematical rules and principles can be applied here to show that in order to compute
(i ^ (N-1)) % N,
you do not even need to compute i^(N-1) at the first place.
You can easily break down (N-1) into powers of 2.
Let's take an example to make it more clear.
Assume that the subject of our primality test, N = 58.
So,
N - 1 = 57
57 can be easily rewritten as:
57 = 1 + 8 + 16 + 32
or,
57 = 2^0 + 2^3 + 2^4 + 2^5
So, substituting this value for N-1, we need to compute
(i ^ (2^0 + 2^3 + 2^4 + 2^5))% 58
or,
((i^1) × (i^8) × (i^16) × (i^32))% 58
Which, using the Modular Multiplication identities, can be rewritten as:
((i^1)% 58 × (i^8)% 58 × (i^16)% 58 × (i^32)% 58) mod 58 ---(1)
Note that,
(i^1)% 58 = i%58
can be easily computed without worrying of any overflows.
Once again utilising the Modular Multiplication identities, we know that
(i^2)% 58 = ((i^1)% 58 × (i^1)% 58)% 58
Substitute the value of (i^1)% 58 to find (i^2)% 58.
You can continue in this fashion, computing (i^4)% 58 through (i^32)% 58. Once completed, you can finally substitute the values in (1) to finally find the required value, very efficiently avoiding any overflows.
Note that, other modular exponientation techniques exist too. This was just an example to showcase how modular mathematical techniques can be used in implementing Fermat's little primality test.
Cheers!