簡體   English   中英

唐津算法:分割中間的數字序列

[英]Karatsuba's algorithm: split the digit sequences about the middle

這是唐津算法的偽代碼:

procedure karatsuba(num1, num2)
    if (num1 < 10) or (num2 < 10)
        return num1*num2

    /* calculates the size of the numbers */
    m = max(size_base10(num1), size_base10(num2))
    m2 = m/2

    /* split the digit sequences about the middle */
    high1, low1 = split_at(num1, m2)
    high2, low2 = split_at(num2, m2)

    /* 3 calls made to numbers approximately half the size */
    z0 = karatsuba(low1, low2)
    z1 = karatsuba((low1+high1), (low2+high2))
    z2 = karatsuba(high1, high2)

    return (z2*10^(2*m2)) + ((z1-z2-z0)*10^(m2)) + (z0)

我不理解“分割中間的數字序列”的步驟,尤其是在看過Karatsuba算法的python實現之后

您能解釋一下,我們應該如何精確分割數字序列?

在每次迭代中,您都將中間的數字按文本長度(以10為基數)折斷。例如,六位數的數字123456變為123456

對於不同長度的數字,請注意,該實現適用於兩者中的最大值。 在給定12345678100 ,此有效值會將較短的數字00000100零, 00000100 分別分成兩個4位數字,然后繼續。

請注意,作為一種算法,這表示簡單的二項式展開式:

(a + b) * (c + d) = ac + ad + bc + bd

在8位數的情況下,我們的數字是

(1234*10^4 + 5678) * (0000*10^4 + 0100)

這有助於您的理解嗎?

我為Karatsuba算法寫了一個非常簡單的代碼,您也可以嘗試...

import timeit
import math
#loading math and time module

start_time = timeit.default_timer()
# creating a start time count down initilise to 0

def karatsuba_multiplication(nu1,nu2):          #defining a function
    num1 = str(nu1)                             #converting inteager into string because object of type inteager has no lenght
     num2 = str(nu2)
     x = len(num1)
     y = len(num2)

    if x == 1 or y == 1:
        print('----result----',nu1*nu2)
    else:
        if x >= y:
            n = x
        else:
            n = y
        if n % 2 == 0:
            n  = n
        else:
            n = n + 1
        a = int(num1[0:math.floor(x/2)])        #slicing the numbers for ltiplication
        b = int(num1[math.ceil(x/2):x])
        c = int(num2[0:math.floor(y/2)])
        d = int(num2[math.ceil(y/2):y])
        print('----reslut----',int((10**n)*(a*c) + (10**(n/2))*(a*d + b*c) + b*d))  
#formula of karatsuba

karatsuba_multiplication(9,1234)
karatsuba_multiplication(7,12345)
karatsuba_multiplication(213,1234)
karatsuba_multiplication(1234,5678)
karatsuba_multiplication(12345,987)
karatsuba_multiplication(314159265358979323846264338327950288419716939937510582097494  
4592,2718281828459045235360287471352662497757247093699959574966967627)

stop = timeit.default_timer()                   #countdown ends here
print('program time--',stop)

可能這段代碼很冗長,但是很簡單。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM