Skip to content

Instantly share code, notes, and snippets.

@making
Last active August 29, 2015 13:55
Show Gist options
  • Save making/8777362 to your computer and use it in GitHub Desktop.
Save making/8777362 to your computer and use it in GitHub Desktop.
aのk乗をmで割った余り = p(a, k, m)
(xy % z) = ((x % z) * (y % z)) % z

k = 2tの場合 a^k = a^t * a^t

p(a, k, m) = (p(a, k/2, m) * p(a, k/2, m)) % m

k = 2t + 1の場合

a^k = a^t * a^t * a

p(a, k, m) = (p(a, k - 1, m) * p(a, 1, m)) % m


function p(a, k, m) {
  if (k == 0) {
    return 1;
  }
  q = p(a, k/2, m);
  
  ret = (q * q) % m;
  
  if (k % 2 == 1) {
    ret = (ret * (a % m)) % m;
  }
  
  return ret;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment