PowerMod[x,p,m] is significantly faster than Mod[x^p, m] for a large p

I have an expression, say 12*5^p + 33*9^p + 15, and I need the value mod 1007 for some integer p. For a large p it's significantly faster to calculate Mod[12*PowerMod[5,p,1007] + 33*PowerMod[9,p,1007] + 15, 1007].

Now, my actual expression is much more complicated and it's a result of previous code. So it's a chore (not to mention error prone) for me to manually add PowerMod at the appropriate places.

My question is, can Mathematica somehow automatically find where to put PowerMod in an expression of the form Mod[expression, 1007]?


1 Answer 1

12*5^p + 33*9^p + 15 /. x_^y_ -> PowerMod[x, y, 1007]


15 + 11 PowerMod[3, 1 + 2 p, 1007] + 12 PowerMod[5, p, 1007]

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.