Calculating Huge Number Modulo
I have stumbled upon a task to calculate modulo of 5 * (2¹⁰)¹⁸
where mod = 10⁹+7
Using multiplication formula
x * y % mod = ((x % mod) * (y % mod)) % mod
we can first split our problem to
(n % mod) * ((2 ¹⁰)¹⁸ % mod) % mod = X
and then to
(n % mod) * ((2 ¹⁰*¹⁸ % mod) % mod = X
Modern programing languages like python can do this already in pow (exponent) function has third parameter for mod.
(5 * pow(2, 10 * 18, mod) ) % mod = 256609439
Interesting enough python pow
support this but math.pow
does not 😬
Behind the scenes language can do this in log(n) complexity using same multiplication principle as described above. Lets implement this ourselves in case your language does not support this like golang.
package main
import "fmt"
const mod int64 = 1e9 + 7
func main() {
fmt.Printf("%d", (5 * pow(2, 10*18) % mod))
}
func pow(base, exp int64) int64 {
var res int64 = 1
for exp > 0 {
if exp&1 == 1 {
res *= base
res %= mod
}
base *= base
base %= mod
exp /= 2
}
return res
}