Don't like ads? PRO users don't see any ads ;-)
Guest

Untitled

By: a guest on May 8th, 2012  |  syntax: None  |  size: 0.47 KB  |  hits: 9  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. size_t modpow(size_t x, size_t power, size_t mod)
  2. {
  3.         /* Only powers of two need to be multiplied together the get the result.
  4.          *
  5.          * Here we use the Euclidean algorithm to retreive those powers,
  6.          * multiplying them together and reducing by the modulus at each iteration
  7.          * to "avoid" overflow (ha!). */
  8.         size_t result = 1;
  9.  
  10.         while (power > 0) {
  11.                 if ((power % 2) == 0) {
  12.                         result = (result * x) % mod;
  13.                 }
  14.  
  15.                 power /= 2;
  16.                 x = (x * x) % mod;
  17.         }
  18.  
  19.         return result;
  20. }