# Can Mathematica automatically optimize an expression with PowerMod?

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]?

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]