如何更快地乘以大数? [英] How to multiply big numbers faster?

查看:59
本文介绍了如何更快地乘以大数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在 python 中乘以大数.为了我的目的,我试图评估.

I was experimenting with multiplying large numbers in python. For my purpose I was trying to evaluate.

2*odd*(4*odd^2 + 7)/3 - 6*odd^2 - 3

现在我的问题归结为如何在 python 中更快地乘以数字.用浮动做它更快吗?答案似乎没有.举个更简单的例子

Now my question boils down to how to multiply numbers faster in python. is it faster to do it with float? The answer seems no. Take a simpler example with

n*(n+1)/2

我的想法是下面的代码更快

My idea was that the following code is faster

product = 1
if n % 2 == 0:
    product *= n/2
    product *= n
else:
    product *= (n+1)/2
    product *= n
return product

为什么这会更快?好吧,您不必将巨大的数字 n*(n+1) 除以 2.但是,确实浪费了检查数字 modulo2 的计算.也许 try exception 更快?

Why would this be faster? Well you would not have to divide the huuge number n*(n+1) by two. However one does waste a calculation checking the number modulo2. Perhaps try exception is faster?

所以我的问题归结为.如何在 python 中计算非常大数的乘积和除法?这是我的工作代码.不要求对此代码进行特别的速度改进.但更广泛的问题是如何处理大数的除法和乘法.我的 numrange 大约是 10^(10^6) atm.

So my question boils down to. How does one compute the product and division of very large numbers in python? Here is my working code. Not asking for specifically speed improvements on this code. But the more broad question on how to deal with division and multiplication of large numbers. My numrange is around 10^(10^6) atm.

def spiral_sum_fast(num):
    rem = num % 6
    if rem % 2 == 0:
        raise Exception("The sidelength must be a odd number")
    odd = 1 + num / 2
    odd_squared = 2 * odd**2

    if rem % 3 == 0:
        temp = odd / 3
        temp *= 8 * odd_squared + 14
    else:
        temp = (4 * odd_squared + 7) / 3
        temp *= 2 * odd
    return temp - 3 * odd_squared - 3


if __name__ == '__main__':

    k = 10**(10**6) + 1
    spiral_sum_fast(k)

推荐答案

一般来说,您应该为专门的工作专门设计库.在您的情况下,处理大量数据并获得最佳速度可能需要这样做.看看这个博客,它处理大数字并进行速度比较纯 Python 并使用 Python 中的 GNU 多精度算术库,从而大大提高了性能.

In general you should specialised libraries for specialised jobs. In your case dealing with large numbers and getting optimal speed might require this. Have a look at this this blog which deals with big numbers and makes speed comparisons between pure Python and using the GNU Multiple Precision Arithmetic Library from Python, which results in a big performance improvement.

这篇关于如何更快地乘以大数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆