Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Implement Karatsuba's Algorithm #26

Open
NMCarv opened this issue Oct 9, 2024 · 0 comments
Open

Implement Karatsuba's Algorithm #26

NMCarv opened this issue Oct 9, 2024 · 0 comments
Assignees
Labels
enhancement New feature or request

Comments

@NMCarv
Copy link
Member

NMCarv commented Oct 9, 2024

As we now have a shift-and-add multiplication algorithm for unsigned integers, that is already faster than similar private compute libraries, we need to implement Karatsuba's algorithm for faster multiplication of larger integers.

This is a Python pseudocode for Karatsuba's:

def karatsuba_uint16(x, y):
    # Base case: if numbers are small, use simple multiplication
    if x <= 255 and y <= 255:
        return x * y

    # Split the numbers into high and low 8-bit parts
    x_high, x_low = x >> 8, x & 0xFF
    y_high, y_low = y >> 8, y & 0xFF

    # Compute the three products
    z0 = karatsuba_uint16(x_low, y_low)
    z2 = karatsuba_uint16(x_high, y_high)
    z1 = karatsuba_uint16((x_low + x_high), (y_low + y_high)) - z2 - z0

    # Combine the results
    return (z2 << 16) + (z1 << 8) + z0

Considerations (for 16-bit implementation):

  1. Splitting numbers:
    x_high = x >> 8 (right shift by 8 bits)
    x_low = x & 0xFF (bitwise AND with 11111111)
  2. Addition (for x_low + x_high and y_low + y_high):
    Implement an 8-bit adder using full adders made of XOR and AND gates.
  3. Subtraction (for z1 - z2 - z0):
    Implement using two's complement addition:
    • Invert all bits (NOT operation)
    • Add 1
    • Then use the adder from step 2
  4. Multiplication (for the base case and final combination):
    • For the base case (8-bit * 8-bit), use a series of AND gates and adders
    • For shifting (<<8 and <<16), simply connect wires to different positions
  5. Recursive structure:
    • We'll need three separate 16-bit multipliers for z0, z1, and z2 (recursive calls)

Resources:

@NMCarv NMCarv added the enhancement New feature or request label Oct 9, 2024
@NMCarv NMCarv added this to the Compute SDK beta milestone Oct 9, 2024
@NMCarv NMCarv self-assigned this Oct 9, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
enhancement New feature or request
Projects
None yet
Development

No branches or pull requests

1 participant