2

I have to create a simple modular exponentiation function that takes input three integers, a, b and c, and performs the task: a^b %c without overflow.

  • 4
    Possible duplicate of [Modular Exponentiation for high numbers in C++](http://stackoverflow.com/questions/2207006/modular-exponentiation-for-high-numbers-in-c) – costrom Jul 14 '16 at 22:29

2 Answers2

1

It is Modular exponentiation. Assuming unsigned a, b, c and that a * (c - 1) does not overflow:

unsigned int r = 1;
for (unsigned int k = 0; k < b; k++)
    r = r * a % c;

(Note that there is no power operator in C, ^ is for XOR (exclosive OR.)

AlexD
  • 32,156
  • 3
  • 71
  • 65
1

Use Euler theorem for this, it can reduce the exponent down significantly.

You'll need a helper function for finding the phi function (or there might be a library with that in it). Then, all you have to do is

(a ^ b) % c => (a ^ (b % phi(c)) % c

That will definitely help reduce the chance of overflow. Further, mod has this property:

a*b % c = (a % c)*b % c

This means if your exponent will cause an overflow, you can half you exponent, and perform the mod on a smaller value. Look into some number theory books for more tricks to make this easier!

Dylan
  • 92
  • 4