I ran into this exact problem just yesterday; my solution was the following: r=mod(mod(a,q)+q,q)