-6

Hello!
I am got stuck in understanding the concept of modular Exponentiation. When I need this and how this works.
Suppose I am calling the power function as : power(2,n-1).
How the loops will be executed for say n=10 and also the time and space complexity for the below problem

#define m 1000000007

unsigned long long int power(unsigned long long int x, unsigned long long int n){

    unsigned long long int res = 1;
    while(n > 0){
        if(n & 1){
            res = res * x;
            res = res % m;
        }
        x = x * x;
        x= x % m;
        n >>= 1;
    }
    return res;

}
Himanshu Ray
  • 38
  • 1
  • 12
  • 1
    Your question "How the loops will be executed for say **n=10**" is not clear. Can't you write the steps out on paper or use a debugger to see what happens in this special case? In any case, your values of **x** and **n** are too small for the modulus operations by **m** to take effect so that is not the best example case. Do you mean to ask how and why that function works in general? – Rory Daulton Aug 08 '17 at 10:50
  • yes @RoryDaulton. how this function works ? – Himanshu Ray Aug 08 '17 at 10:52
  • 2
    Do a search for "exponentiation by squaring" which will explain everything except the `% m` lines, which are there to make everything modulo `m`. If there is something in those explanations you do no understand, then come back and ask for more detail. – Rory Daulton Aug 08 '17 at 10:55
  • note that: (a * b) mod m == ((a mod m) * (b mod m)) mod m This relationship can be used to keep the intermediate values within range. – Richard Critten Aug 08 '17 at 11:24

1 Answers1

5

From the modulo laws on DAle's linked Wikipedia page (on your previous question), we can obtain two formulas:

enter image description here

From the first formula it is clear that we can iteratively calculate the modulo for n from the result for n / 2. This is done by the lines

x = x * x;
x = x % m;

There are thus log n steps in the algorithm, because each time the exponent of x doubles. The step counting is done by n >>= 1 and while (n > 0), which counts log n steps.

Now, you may be wondering 1) why doesn't this part set the value of res, and 2) what is the purpose of these lines

if(n & 1){
   res = res * x;
   res = res % m;
}

This is necessary as at certain points in the iteration, be it the start or the end, the value of n may be odd. We can't just ignore it and keep using formula 1, because that means we would skip a power of x! (Integer division rounds down, so e.g. 5 >> 1 = 2, and we would have x^4 instead of x^5). This if statement handles the case when n is odd, i.e. n % 2 = n & 1 = 1. It simply uses formula 2 above to "add" a single power of x to the result.

meowgoesthedog
  • 13,415
  • 4
  • 20
  • 34