Reputation: 2269
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.
Upvotes: 3
Views: 4624
Reputation: 1
This javascript code handles very large values of n correctly.
function fastMod(n, m){
var pow2 = 2
var result = 1
while(n > 0){
if(n&1){
result = (result * pow2) % m
}
n/=2
pow2 = (pow2 * pow2) % m
}
console.log(result)
}
fastMod(77, 100)
Upvotes: 0
Reputation: 477
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
Upvotes: 3
Reputation: 241
Fermat's little theorem can help you in the cases where m is a prime number:
If
p
is a prime number, then for any integera
, the numbera^p − a
is an integer multiple ofp
.For example, if
a = 2
andp = 7
,2^7 = 128
, and128 − 2 = 7 × 18
is an integer multiple of7
.
Upvotes: -1
Reputation: 116
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;
}
Upvotes: 1