[英]What is the best way to compute very large exponents?
I'm new to Python, and I'm trying to solve a programming problem where I have to compute 5 to the n th power, and once I have that, I just have to output the last two digits of that number.我是 Python 的新手,我正在尝试解决一个编程问题,我必须计算 5 的 n次方,一旦我有了这个,我只需要 output 该数字的最后两位数。 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
该代码在大多数情况下工作正常,但当输入为
1000000000000000000
之类的大数字时,超过了 500 毫秒的时间限制
What is the most efficient way to process such large inputs like this as an exponent without exceeding the time limit?在不超过时间限制的情况下处理如此大的输入作为指数的最有效方法是什么?
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.可以通过归纳法证明 5^n mod 100 = 25,对于所有 n >= 2。这在 n = 2 时很明显。假设 5^n 的形式为 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.
然后 5^(n+1) = 100(5k+1)+25,因此 5^(n+1) mod 100 = 25。因此,对于所有 n >= 2,5^n 的最后两位数是 25 .
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.一些有效计算 a^n mod b 的通用技巧包括重复平方计算 a^n,以及在每个步骤中计算余数以使数字保持较小。
For these kinds of heavy calculations you can use Multi Processing to use CPU cores to break down the calculation to little calculation simultaneously.对于这些繁重的计算,您可以使用多处理来使用 CPU 内核同时将计算分解为少量计算。 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.
例如(dummy example)我们知道 5^4 等于 625。所以我们可以使用 2 个 CPU 核心计算 5^2,然后乘以结果。 5^2 * 5^2 = 625.
5^2 * 5^2 = 625。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.