大整数乘法的算法代码
时间: 2023-08-01 21:06:29 浏览: 114
关于大整数乘法的C++算法
4星 · 用户满意度95%
大整数乘法算法一般有两种,一种是传统的竖式乘法,另一种是Karatsuba算法。以下是这两种算法的Python代码实现:
1. 竖式乘法:
```
def multiply(num1, num2):
if num1 == "0" or num2 == "0":
return "0"
m, n = len(num1), len(num2)
res = [0] * (m + n)
for i in range(m-1, -1, -1):
for j in range(n-1, -1, -1):
mul = int(num1[i]) * int(num2[j])
p1, p2 = i+j, i+j+1
s = mul + res[p2]
res[p1] += s // 10
res[p2] = s % 10
i = 0
while i < len(res) and res[i] == 0:
i += 1
return "".join(map(str, res[i:]))
```
2. Karatsuba算法:
```
def karatsuba(num1, num2):
if len(num1) < len(num2):
num1, num2 = num2, num1
if len(num2) == 0:
return "0"
if len(num1) <= 50:
return str(int(num1) * int(num2))
m = len(num1) // 2
a, b = num1[:m], num1[m:]
c, d = num2[:m], num2[m:]
z0 = karatsuba(a, c)
z1 = karatsuba(b, d)
z2 = karatsuba(str(int(a)+int(b)), str(int(c)+int(d)))
return str(int(z0) * 10**(2*m) + (int(z2)-int(z0)-int(z1)) * 10**m + int(z1))
```
其中,竖式乘法适用于两个数位数比较小的情况,而Karatsuba算法则适用于两个数位数比较大的情况。
阅读全文