I have a question, how does
pow(num, power, mod)
work so much faster than
(num**power)%mod
On large numbers the second is unusable, so i'm wondering how pow() works. How does it work to be so much faster, what is the underpinning of how it works with mod to calculate an answer so much faster than
(num**power)%mod.
(num * * power)%mod is unusable with larger numbers
so i'm wondering what trick pow() uses to calculate the answer so quickly? Does it mod first, then power? Hopefully somebody can help me understand how this works.
import time shared_Prime = 1031267 base_prime = 111029 secret_num = 103123 start = time.time() A = (secret_num**base_prime) % shared_Prime end = time.time() print(end - start) 0.1082313060760498 start = time.time() B = pow(secret_num, base_prime, shared_Prime) end = time.time() print(end - start) 8.916854858398438e-05 A==B True
anatolyg.. 6
You can experience this as a human being. Suppose you want to answer the following question:
What is the last digit in a decimal representation of 3100?
To answer this, you can calculate 3100 while tracking only the last digit:
3^5 = 243 = 3 mod 10 3^25 = (3^5)^5 = 3 mod 10 3^50 = (3^25)^2 = 9 mod 10 3^100 = (3^50)^2 = 1 mod 10
So the last digit is 1. Now imagine calculating all digits of 3100, just to throw them all away, except for the last one... Too tedious to be practical.
The considerations above hold also for calculation in python.
You can experience this as a human being. Suppose you want to answer the following question:
What is the last digit in a decimal representation of 3100?
To answer this, you can calculate 3100 while tracking only the last digit:
3^5 = 243 = 3 mod 10 3^25 = (3^5)^5 = 3 mod 10 3^50 = (3^25)^2 = 9 mod 10 3^100 = (3^50)^2 = 1 mod 10
So the last digit is 1. Now imagine calculating all digits of 3100, just to throw them all away, except for the last one... Too tedious to be practical.
The considerations above hold also for calculation in python.