Karatsuba算法:在中间分割数字序列

2024-05-08 15:16:42 发布

您现在位置:Python中文网/ 问答频道 /正文

以下是karatsuba算法的伪代码:

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)

我不理解“在中间分割数字序列”这一步骤,尤其是在查看了的python实现之后 Karatsuba's algorithm

你能给我解释一下,我们到底该怎么分位吗?你知道吗


Tags: thesizereturnsplitnumbersm2z0z2
2条回答

我已经写了一个非常简单的代码为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)

可能这段代码很长,但很简单。你知道吗

在每次迭代中,将中间的数字按文本长度(以10为基数)打断。例如,六位数123456变成123456。你知道吗

对于不同长度的数字,请注意,该实现使用两个中的最大值。在给定12345678100的情况下,这个有效的方法将较短的数字用零填充到00000100。分成两个4位数的数字,然后继续。你知道吗

请注意,作为一种算法,这表示简单的二项式展开:

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

在8位数的情况下,我们的数字是

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

这有助于你的理解吗?你知道吗

相关问题 更多 >