0

I try two function for modular exponentiation for big base return wrong results, One of the function is:

uint64_t modular_exponentiation(uint64_t x, uint64_t y, uint64_t p) 
{ 
    uint64_t res = 1;      // Initialize result 
    x = x % p;  // Update x if it is more than or  
                // equal to p 
    while (y > 0) 
    { 
        // If y is odd, multiply x with result 
        if (y & 1) 
            res = (res*x) % p;   
        // y must be even now 
        y = y>>1; // y = y/2 
        x = (x*x) % p;   
    } 
    return res; 
}

For input x = 1103362698 ,y = 137911680 , p=1217409241131113809; It return the value (x^y mod p):749298230523009574(Incorrect).

The correct value is:152166603192600961

The other function i try, gave same result, What is wrong with these functions? The other one is :

long int exponentMod(long int A, long int B, long int C) 
{ 
    // Base cases 
    if (A == 0) 
        return 0; 
    if (B == 0) 
        return 1; 
    // If B is even 
    long int y; 
    if (B % 2 == 0) { 
        y = exponentMod(A, B / 2, C); 
        y = (y * y) % C; 
    } 
    // If B is odd 
    else { 
        y = A % C; 
        y = (y * exponentMod(A, B - 1, C) % C) % C; 
    }   
    return (long int)((y + C) % C); 
} 
superstack
  • 91
  • 5
  • 1
    If `x` = 1103362698, `y` = 137911680 , and `p`=137911680 then 152166603192600961 can't be the correct value because it it larger than `p`. I got 136204416 when I ran this function with those parameters. – dbush Sep 06 '19 at 17:33
  • And according to https://www.dcode.fr/modular-exponentiation this is the correct answer. – dbush Sep 06 '19 at 17:45
  • sorry p=152166603192600961, I already edit my question – superstack Sep 06 '19 at 17:57

1 Answers1

0

With p = 1217409241131113809, this value as well as any intermediate values for res and x will be larger than 32 bits. This means that multiplying two of these numbers could result in a value larger than 64 bits which overflows the datatype you're using.

If you restrict the parameters to 32 bit datatypes and use 64 bit datatypes for intermediate values then the function will work. Otherwise you'll need to use a big number library to get correct output.

dbush
  • 205,898
  • 23
  • 218
  • 273