Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Modulus power of big numbers

I am trying to implement the SAFER+ algorithm. The algorithm requires finding the modulus of a power function as follows:

pow(45, x) mod 257

The variable x is a byte, and thus can range from 0 to 255. Accordingly, the result of the power function can be VERY big resulting in incorrect values if implemented using 32- or 64-bit integers.

How can I perform this calculation?

like image 475
Eng. Aws Avatar asked Nov 27 '11 16:11

Eng. Aws


People also ask

What is a 100 mod 7?

100 mod 7 = 2 100 is the dividend, 7 is the divisor (modulo), 14 is the quotient explained below, and 2 is called the remainder. The division rest of 100 by 7 equals 2, and the value of the quotient is 14.


2 Answers

some pseudo code

function powermod(base, exponent, modulus) {
    if (base < 1 || exponent < 0 || modulus < 1)
        return -1

    result = 1;
    while (exponent > 0) {
       if ((exponent % 2) == 1) {
           result = (result * base) % modulus;
       }
       base = (base * base) % modulus;
       exponent = floor(exponent / 2);
    }
    return result;
}

and call

powermod(45, x, 257)    
like image 189
esskar Avatar answered Sep 26 '22 02:09

esskar


Perform the exponentiation by repeated squaring, reducing by the modulus after each operation. This is a very standard technique.

A worked example: 45^13 mod 257:

  1. First compute 45^2, 45^4, 45^8 mod 257:

    45^2 mod 257 = 2025 mod 257 = 226

    45^4 mod 257 = 226^2 mod 257 = 51076 mod 257 = 190

    45^8 mod 257 = 190^2 mod 257 = 36100 mod 257 = 120

  2. Then use the binary expansion of 13 to combine these to get the result:

    45^13 mod 257 = 45^1 * 45^4 * 45^8 mod 257

    45^13 mod 257 = 45 * 190 * 120 mod 257

    45^13 mod 257 = 8550 * 120 mod 257

    45^13 mod 257 = 69 * 120 mod 257

    45^13 mod 257 = 8280 mod 257

    45^13 mod 257 = 56

Note that the intermediate results of the computation are never larger than 257*257, so this can easily be performed in a 32-bit integer type.

like image 27
Stephen Canon Avatar answered Sep 26 '22 02:09

Stephen Canon