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).
Asked
Active
Viewed 2,339 times
1
-
How did he manage to store such a large value of B. – Bipul Kumar Feb 26 '21 at 04:23
1 Answers
2
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

MD. MOSHIUR RAHMAN
- 21
- 3