This is the code I\'m using for calculating (n^p)%mod. Unfortunately, it fails for large values of mod (in my case mod = 10000000000ULL) w
(n^p)%mod
mod
mod = 10000000000ULL
Your code line
n = (n*n)%mod;
is repeatedly executed. As long as n is smaller than mod, this will potentially result in evaluating (mod-1)*(mod-1) at some point in time.
On input n may not be so large, but the mentioned line of code increases n in the loop.