I need to calculate a*a mod n but a is fairly large, resulting in overflow when I square it. Doing ((a % n)*(a % n)) % n
a*a
n
a
((a % n)*(a % n)) % n
You can implement the multiplication yourself, adding n each run, and mod'ing the result right away.