Calculate pow(4, p) - 1
modulo 3*q
, and divide the result by 3. To do the exponentiation, use a Modular exponentiation algorithm.
Edit: This will give you integer division (i.e. rounding down the result). See @lisyarus's answer for division in the ring of integers modulo q
.
If q
is not divisible by 3 then both answers should give the same result, because pow(4, p) - 1
is always divisible by 3 so the rounding-down of integer division won't come into play. If q
is divisible by 3 then there is no multiplicative inverse and only this method can be used.