I was wandering if there is any possible efficient way of finding the Remainder when 2^n is divided by m where n and m are random integers. Is there any equation where I sub n and m into to give me the remainder or do we have to follow recursive methods? Do note that I am a beginner and I'm just starting out so might not understand stuff that is too complicated.
Thanks in advance.
fkdosilovic's answer is correct but not the fastest.
His algorithm runs in O(n) time, but it is possible to achieve O(log(n)).
Since all numbers 2^n can be represented as products from a set {2^1, 2^2, 2^4, 2^8 ..., 2^floor(lg(n))}, we only need to compute these values and multiply them. E.g. 2^13 = 2^1 * 2^4 * 2^8. Here is a python code.
def fast_powmod(n, m):
    pow2 = 2
    result = 1
    while n > 0:
        if n % 2 == 1:
            result = (result * pow2) % m
        pow2 = (pow2 * pow2) % m
        n >>= 1
    return result
                        Modular arithmetic for multiplication works like this:
(a * b) % x = ( (a % x) * (b % x) ) % x
Here is C++ code for that:
#include <cstdio>
#include <cstdlib>
using namespace std;
int powmod(int n, int m) {
  int ret = 1;
  for(int i = 0; i < n; ++i)
    ret = ( (ret % m) * (2 % m) ) % m; // expression from above
  return ret; // returns 2 to the power n modulo m
}
int main() {
  int n, m; scanf("%d%d", &n, &m);
  printf("%d\n", powmod(n, m));
  return 0;
}
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With