Advertisement
Guest User

Untitled

a guest
Aug 12th, 2017
79
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 0.85 KB | None | 0 0
  1. /************************************************************************
  2.   Computes base^exp mod (mod) (modular exponentiation) using the
  3.   algorithm square-and-multiply. Returns a 16 bit number.
  4.  
  5.   base   16 bits positive integer
  6.   exp    16 bits positive integer
  7.   mod    16 bits positive integer
  8.  
  9. *************************************************************************/
  10. unsigned short power(unsigned short base, unsigned short exp,
  11.                                           unsigned short mod) {
  12.    
  13.    unsigned long result=1;
  14.    
  15.    while (exp>0) {
  16.       /* Exp is odd, bitwise test */
  17.       if (exp & 1) {
  18.          result=(base*result) % mod;
  19.       }
  20.       base=(base*base) % mod;
  21.       exp/=2;     /* Integer division, rounds down */
  22.    }
  23.    /* Will not truncate since mod is unsigned short */
  24.    return (unsigned short)result;
  25. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement