Nine Chapters count judges Net-original website
http://www.jiuzhang.com/problem/64/
Topics
Computes (a^n)%b, where a, B and N are all 32-bit integers. For example (2^31)%3 = 2.
Online test
http://lintcode.com/zh-cn/problem/fast-power/
Answer
First we need to know a theorem for the MoD operation:
(A * b)% P = (a% p * b% p)% p
By this theorem we can know
Original A^n% B
1. If n is an odd number can be converted to (a^ (N/2) * a^ (N/2) * a)%b = ((a^ (N/2)%b * a^ (N/2)%b)%b * (a)%b)%b
2. If n is an even number can be converted to (a^ (N/2) * a^ (N/2))%b = (a^ (N/2)%b * a^ (N/2)%b)%b
Because know a^1 = A, a^0=1,
And then recursively go for a^n, so that each time we have two minutes n, our actual time complexity is O (log (n)).
So when n is particularly large, then exponentiation becomes particularly fast.
Nine-Chapter algorithm surface question 63 fast power