Different ways for modular exponentiation $A^E$ with negative A's
For any integer $A$ we have the congruence $A \equiv A + kn \text{ mod } n$ for all integers k. This means a generic algorithm to get $A$ (where $A &lt; 0$) into the range $[0, n)$ would be something like:

function(A):
    while(A &lt; 0):
        A = A + n
    return A


Doing A = A % n will work in some languages as well (e.g. python) but not all languages (e.g. C).