当前位置:  开发笔记 > 编程语言 > 正文

Why is pow(num, power, mod) so much faster than (num ** power) % mod?

如何解决《Whyispow(num,power,mod)somuchfasterthan(num**power)%mod?》经验,为你挑选了1个好方法。

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.



1> anatolyg..:

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.

推荐阅读
大大炮
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有