Tuesday, 15 April 2014

java - why this function is valid to caculate modular pow value? -


I have seen this function in

  long modpow (long x, long y) {// Caculates x was increased using the repeated square-length r = 1 in the y-power modulo MOD / i (log (y)); Whereas (y> gt; 0) {if ((y and 1)! = 0) {r = (r * x)% MOD; } X = (x * x)% MOD; Y & gt; & Gt; = 1; } Return R; }   

But I am confused with this function to index the modular value of x ^ y% MOD ; Code> x = (x * x)% MOD; What is required in the function?
It does not seem to be as I think.

tl; Dr: This is a customization.

Imagine that x 2 and MOD 3 are. Keep in mind that only one thing is used for X which is multiplied by x.

Now imagine that we square x x * x = 4. now, r * 4% 3 is equal to 1, 2, 3, 4, 5 ... for r = 1, 2, 3, 4, 5 ... oh! This is exactly like x 1. In fact, if you set x * x * 3 instead of x * x, you get the same result.

But what about the next step? 4 * 4 = 16,% 3 = 1. 1 * 1 = 1,% 3 also = 1 If we stop the operation early or late or ever, then we are stuck on the same residual.

No comments:

Post a Comment