Main Menu

search

You are here

Mathematics: Karatsuba Algorithm

[last updated: 2021-08-01]
go to: ...
-----

  • The Karatsuba algorithm is used to multiply very large integers. It is generally faster when the operands are larger than 500 digits (very approximate)

  • given two large numbers, x & y
    set n = number of digits of the larger one
    set m = (n // 2) + 1
  • Then:
    x = x1 x 10m + x0
    y = y1 x 10m + y0
  • Calculate interim quantities:
    z0 = x0 y0
    z1 = x1 y0 + x0 y1
    z2 = x1 y1
  • Then:
    x y = z2 * 102m + z1 * 10m + z0
    -------------------------------------------------------------------------

  • For example:
    • x = 12345
      y = 6789
    • n = 5
      m = 3
    • x = 12 x 103 + 345
      y = 6 x 103 + 789
        Or:
        x1 = 12
        x0 = 345
        y1 = 6
        y0 = 789

    • z0 = x0 y0
      z0 = 345 * 789 = 272205


      z1 = x1 y0 + x0 y1
      z1 = (12 * 789) + (345 * 6) = 11538


      z2 = x1 y1
      z2 = 12 * 6 = 72

    • x y = z2 * 102m + z1 * 10m + z0
            = 72 * 106 + 11538 * 103 + 272205
            = 72,000,000 + 11,538,000 + 272,205
            = 83,810,205

  • In the python program I wrote to implement this algorithm, it performed 20x slower than standard multiplication for operands up to about 30-digits.

.

.

.

eof