Search code examples
algorithmrecursioncomplexity-theorymodular

2^n mod (m) algorithm


In class, we were presented with an algorithm for 2^n mod(m).

    to find 2^n mod(m){  
      if n=0 {return 1;}  

      r=2^(n-1)mod(m);  
      if 2r < m {return 2r;}  
      if 2r > =m {return 2r-m;}  
    }

We were told that the runtime is O(n*size(m)) where size of m is the number of bits in m.

I understand the n part, but I cannot explain the size(m) unless it is because of the subtraction involved. Can anyone shed some light on that?

Thanks in advance.


Solution

  • The n part is clear, as you have already understood yourself. The size(m) (which is the number of digits in m, which is basically log(m)) is because of mod. Even though your CPU does that for you in one instruction, it takes log(m) (let's say 32 bits) times. If m is very large, as is common with encryption keys, this can become considerable.

    Why number of digits in m? Remember division:

    abcdefghijk | xyz
                |-----
    alm         | nrvd...
     opq
      stu
       wabc
        .......
    

    The number of times you do the minus, is at most the number of digits in the dividend.