计算非常大的指数的最佳方法是什么?
我是Python的新手,我正在尝试解决一个编程问题,其中我必须将5计算为N th Power,一旦我拥有,我只需要输出最后两个该数字的数字。这是我下面写的代码:
print(str(pow(5, int(input())))[-2:])
大多数情况下,该代码正常运行,但是当输入是大数字之类的大量时,超过了500毫秒的时间
限制像这样的大量输入是指数,而没有超过时间限制?
I'm new to Python, and I'm trying to solve a programming problem where I have to compute 5 to the nth power, and once I have that, I just have to output the last two digits of that number. This is the code I wrote below:
print(str(pow(5, int(input())))[-2:])
The code works fine, for the most part, but exceeds the 500 ms time limit when the input is a large number like 1000000000000000000
What is the most efficient way to process such large inputs like this as an exponent without exceeding the time limit?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
可以通过诱导表明5^n mod 100 = 25,对于所有n> = 2。当n = 2时,这很明显。假设5^n是100k+25的形式。然后5^(n+1)= 100(5k+1)+25,其中5^(n+1)mod 100 = 25。因此,所有n> = = 25 = 25。 2。
有效地计算A^n mod b的一些一般技巧包括用于计算A^n的重复平方,并且在每个步骤中计算保留数量,以使数字保持较小。
It can be shown by induction that 5^n mod 100 = 25, for all n >= 2. This is clear when n = 2. Suppose 5^n is of the form 100k+25. Then 5^(n+1) = 100(5k+1)+25, whence 5^(n+1) mod 100 = 25. Hence, the last two digits of 5^n is 25, for all n >= 2.
Some general tricks for computing a^n mod b efficiently include repeated squaring for computing a^n, and computing remainders in each step so that the numbers stay small.
对于这类重型计算,您可以使用多处理来使用CPU核心将计算分解为几乎没有计算。
例如(虚拟示例)我们知道5^4等于625。因此,我们可以使用2个核心CPU来计算5^2,然后乘以结果。 5^2 * 5^2 = 625。
For these kinds of heavy calculations you can use Multi Processing to use CPU cores to break down the calculation to little calculation simultaneously.
For example (dummy example) we know 5^4 equals to 625. So we can use 2 cores of CPU to calculate 5^2, then multiply the result. 5^2 * 5^2 = 625.