简体   繁体   English

计算非常大的指数的最佳方法是什么?

[英]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.

相关问题 在python中计算非常大的指数 - Calculating very large exponents in python plot 一个非常大的 pandas dataframe 的最佳方法是什么? - What's the best way to plot a very large pandas dataframe? 计算具有复数的非常大的矩阵的欧几里得距离的最快方法是什么? - What is the fastest way to compute the Euclidean distances of a very large matrix with complex numbers? 在MySQL数据库中存储和查询大量可变长度列表的最佳方法是什么? - What is the best way to store and query a very large number of variable-length lists in a MySQL database? 在非常大规模的加权和有向图中获得所有对最短路径的最佳方法是什么? - what is the best way to get all pair shortest path in very large scale weighted and directed graph? 最好的下载方式是什么<very large>网址列表中的页数? - What is the best way to download <very large> number of pages from a list of urls? 计算变压器结果指标的最佳方法是什么? - What is the best way to compute metrics for the transformers results? 计算大型列表的方法 - Way to compute large lists 从非常大的 BigQuery 表中读取小批量的最佳方法? - Best way to read minibatches from a very large BigQuery table? Python - 在超大文本文件 (8GB) 中查找数据的最佳方式 - Python - Best way to find data in a very large textfile (8GB)
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM