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

refactor: optimize uint128 multiplication using Karatsuba algorithm #11616

Closed
wants to merge 4 commits into from

Conversation

crStiv
Copy link

@crStiv crStiv commented Jan 30, 2025

Implements Karatsuba algorithm for uint128_t multiplication, reducing multiplications from 4 to 3 operations:

  • Standard algorithm: 4 multiplications (a_hi * b_hi, a_hi * b_lo, a_lo * b_hi, a_lo * b_lo)
  • Karatsuba algorithm: 3 multiplications (z0 = a_lo * b_lo, z2 = a_hi * b_hi, z1 = (a_lo + a_hi)(b_lo + b_hi) - z0 - z2)
  • Theoretical improvement: (4-3)/4 * 100% = 25%

Includes safe overflow handling with fallback and full test coverage.

@ludamad
Copy link
Collaborator

ludamad commented Jan 31, 2025

~X% performance improvement you have neglected the most important part of this PR description

@crStiv
Copy link
Author

crStiv commented Feb 1, 2025

~X% performance improvement you have neglected the most important part of this PR description

@ludamad you're right. My bad.

In theory it should be 25%.

Standard algorithm uses 4 multiplications:

  • a_hi * b_hi
  • a_hi * b_lo
  • a_lo * b_hi
  • a_lo * b_lo

Karatsuba reduces this to 3 multiplications:

  • z0 = a_lo * b_lo
  • z2 = a_hi * b_hi
  • z1 = (a_lo + a_hi)(b_lo + b_hi) - z0 - z2

Theoretical improvement: (4-3)/4 * 100% = 25%

P.S. I've updated the PR description.

@ludamad
Copy link
Collaborator

ludamad commented Feb 1, 2025

But what was it actually, surely you ran your own code?

@ludamad
Copy link
Collaborator

ludamad commented Feb 1, 2025

Closing as you seem to be giving us code you didn't investigate at all.

@ludamad ludamad closed this Feb 1, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants