Reputation: 11
Link to the problem: https://www.hackerearth.com/problem/algorithm/rhezo-and-big-power/description/ I saw the best submission in which the person calculated A%M (just like how we do on paper), and B%(M-1); then these two came in Integer range and he did log(n) approach to find m^n % M? I can't really understand why would he do B%(M-1).
Upvotes: 1
Views: 2442
Reputation: 21
According to Fermat's little theorem,
a^(p-1) mod p = 1, When p is prime.
From this, As of the problem, M is prime, we can express A^B mod M as following,
A^B mod M = ( A^(M-1) * A^(M-1) *.......* A^(M-1) * A^(x) ) mod M
Where x is B mod M-1 and A ^ (M-1) continues B/(M-1) times
Now, From Fermat's Little theorem, A ^ (M-1) mod M = 1.
Hence,
A^B mod M = ( 1 * 1 * ....... * 1 * A^(x) ) mod M
This is why, we mod B with M-1
Upvotes: 2