问题描述
所以,有一天我在python中尝试一些东西,我试图在python中编写自定义乘法函数
def multi(x,y):
z = 0
而y> 0:
z = z + x
y = y-1
返回z
但是,当我以极大的数字运行它时,例如(1 因此,我尝试研究了不同类型的乘法,例如在那里实施的俄罗斯农民乘法技术,该方法非常快,但不如multi(x,y)可读。
def Russian_peasant(x,y):
z = 0
而y> 0:如果y%2 == 1,则
:z = z + x
x = x< 1
y = y>> 1
return z
我想让您回答的是python之类的编程语言如何乘法数字?
您的 multi
版本以O(N)运行,而 russian_peasant
版本以O(logN)运行,比O(N)更好。
了解您的速度有多快 russian_peasant
版本是,请检查此
来自数学导入日志
print round(log(100000000,2))#27.0
因此,循环必须是仅执行了27次,但是当 y
为100000000时,您的 multi
版本的while循环必须执行100000000次。 / p>
要回答其他问题,
Python使用,但用于。
基本乘法是用C代码处理的,可以编译为机器代码并更快地执行。
So the other day I was trying something in python, I was trying to write a custom multiplication function in python
def multi(x, y):
z = 0
while y > 0:
z = z + x
y = y - 1
return z
However, when I ran it with extremely large numbers like (1 << 90) and (1 << 45) which is (2 ^ 90) * (2 ^ 45). It took forever to compute.So I tried looking into different types of multiplication, like the russian peasant multiplication technique, implemented down there, which was extremely fast but not as readable as multi(x, y)
def russian_peasant(x, y):
z = 0
while y > 0:
if y % 2 == 1: z = z + x
x = x << 1
y = y >> 1
return z
What I want you to answer is how do programming languages like python multiply numbers ?
Your multi
version runs in O(N) whereas russian_peasant
version runs in O(logN), which is far better than O(N).
To realize how fast your russian_peasant
version is, check this out
from math import log
print round(log(100000000, 2)) # 27.0
So, the loop has to be executed just 27 times, but your multi
version's while loop has to be executed 100000000 times, when y
is 100000000.
To answer your other question,
Python uses O(N^2) grade school multiplication algorithm for small numbers, but for big numbers it uses Karatsuba algorithm.
Basically multiplication is handled in C code, which can be compiled to machine code and executed faster.
这篇关于为什么python的内置乘法如此快的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!