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.
The
npart is clear, as you have already understood yourself. Thesize(m)(which is the number of digits inm, which is basicallylog(m)) is because of mod. Even though your CPU does that for you in one instruction, it takeslog(m)(let’s say 32 bits) times. Ifmis very large, as is common with encryption keys, this can become considerable.Why number of digits in
m? Remember division:The number of times you do the minus, is at most the number of digits in the dividend.