大整數乘法

Alocus_發表於2020-12-14
import sys

s = sys.stdin.readline().strip().split()


def karatsuba_mul(num1, num2):
    # karatsuba演算法
    if len(str(num1)) == 1 or len(str(num2)) == 1:
        return num1 * num2
    n = max(len(str(num1)), len(str(num2)))
    half = n // 2

    a = num1 // 10 ** half
    b = num1 % 10 ** half
    c = num2 // 10 ** half
    d = num2 % 10 ** half
    ac = karatsuba_mul(a, c)  # 計算a*c
    bd = karatsuba_mul(b, d)  # 計算b*d
    abcd = karatsuba_mul(a + b, c + d)  # 計算(a+b)*(c+d)
    adbc = abcd - ac - bd
    return ac * 10 ** (2 * half) + adbc * 10 ** half + bd


print(str(karatsuba_mul(int(s[0]), int(s[1]))))

k_multi()
	//遞迴呼叫k_multi來對num1和num2實現乘法
	//輸入:兩個數字:num1 ,num2
	//輸出:兩數相乘結果
	if (num1<10)or (num2<10)
		return num1*num2
	length = max(len(num1),len(num2))
	half = length/2
	a,b = num1 / 10 ** half,num1 % 10 ** half
	c,d = num2 / 10 ** half,num2 % 10 ** half
	//遞迴計算
	ac = k_multi(a,c)
	bd = k_multi(b,d)
	abcd = k_multi(a+b,c+d)
	adbc = abcd - ac - bd
	return ac*10**half + adbc*10**half + bd
演算法時間複雜度T(n) = 3T(n/2) + f(n)
其中加法運算f(n)的時間複雜度可以看為cn
由主定理得:T(n) ∈ Θ(nlog23)