Your basic algorithm is correct, although you will have to use a larger data type than int if you want to do this for non-trivial numbers.
You should not implement modular exponentiation the way you did, because the intermediate result is huge. Here is a square and multiplicable algorithm for modular exponentiation:
function powerMod(b, e, m) x := 1 while e > 0 if e%2 == 1 x, e := (x*b)%m, e-1 else b, e := (b*b)%m, e//2 return x
As an example, 437 ^ 13 (mod 1741) = 819. If you use the algorithm shown above, the intermediate result will not be more than 1740 * 1740 = 3027600. But if you first raise, the intermediate result 437 ^ 13 is 21196232792890476235164446315006597, which you probably want to avoid.
Even so, the Fermat test is imperfect. There are some compound numbers, Carmichael numbers, which will always report the main thing, no matter which witness you choose. Look for the Miller-Rabin test if you want something that will work better. I modestly recommend this essay on programming with Prime Numbers on my blog.
source share