Skip to content
Gyunseo's Blog
Go back

Karastuba Algorithm (카라추바 알고리즘)

Suggest Changes

Table of contents

Open Table of contents

들어가며

카라추바(Karastuba) 알고리즘은 소련의 수학자 아나톨리 알렉세예비치 카라추바가 1960년에 발견하고, 1962년에 공개한, 큰 정수에 대한 효과적인 곱셈 알고리즘

기본적으로 x*y의 곱셈연산은 O(n2)O(n^2)이라는 연산횟수가 필요.

카라추바(Karastuba): 큰 두 수 xy의 곱을 자릿수가 x, y의 절반인 수들의 곱, 3번과 덧셈과 시프트 연산을 이용해 연산 횟수를 줄임. -> Time Complexity가 줄어듦.

얼마나 줄어드나요?

알고리즘

xyxy의 연산을 위해, 하기와 같이 쪼갬. x=x1Bm+x0x=x_1B^m+x_0
y=y1Bm+y0y=y_1B^m+y_0

예: 48 * 53

xy=(x1×Bm+x0)(y1×Bm+y0)=L×B2m+M×Bm+NL=x1y1M=x0y1+x1y0=L+N(x1x0)(y1y0)N=x0y0\begin{align} xy = (x_1 \times B^m + x_0)(y_1 \times B^m + y_0) \newline = L \times B^{2m} + M \times B^m + N \newline L = x_1y_1 \newline M = x_0y_1 + x_1y_0 \newline = L + N - (x_1 - x_0)(y_1 - y_0) \newline N = x_0y_0 \end{align}

L = 20, N = 20, M = 20 + 24 - (4 - 8)(5 - 3) = 52 xy = 20 * 10^2 + 52 * 10^1 + 24 = 2000 + 520 + 24 = 2544

python 코드

import sys

sys.setrecursionlimit(10**9)


def get_karatsuba(x, y):
    if x < 10 or y < 10:
        return x * y

    n = max(len(str(x)), len(str(y)))
    n2 = n // 2

    a = x // 10**n2
    b = x % 10**n2
    c = y // 10**n2
    d = y % 10**n2

    ac = get_karatsuba(a, c)
    bd = get_karatsuba(b, d)
    ad_bc = get_karatsuba(a + b, c + d) - ac - bd

    result = ac * 10 ** (2 * n2) + ad_bc * 10**n2 + bd

    return result


if __name__ == "__main__":
    x = 2462
    y = 8014
    print(get_karatsuba(x, y))

How to Run

python version: 3.11.6

Run main.py

pip install pipenv
pipenv --python 3.11.6
pipenv run python3 main.py

Input

24628014를 곱하는 상황

Output

19730468

Execution Image


Suggest Changes
Share this post on:

Previous Post
Strassen's Matrix Multiplication
Next Post
OSTEP 37 File Disks