akaratsuba.py

Created by bilouclic

Created on December 15, 2024

596 Bytes


def taille(x: int) -> int:
''' renvoie le nombre de chiffres de l’entier x lorsqu’il est écrit en base 2. '''
return len(bin(x)) - 2

def karatsuba(x: int, y: int, k: int) -> int:
''' calcule le produit de x et de y par la méthode de Karatsuba. '''
if k > 2:
a, b = x >> k, x % (1 << k)
c, d = y >> k, y % (1 << k)
k2 = k >> 1
p1 = karatsuba(a, c, k2)
p2 = karatsuba(b, d, k2)
p3 = karatsuba(a - b, c - d, k2)
return (p1 << (2 * k)) + ((p1 + p2 - p3) << k) + p2
else: return x * y

def mult(x: int, y: int) -> int:
n = max(taille(x), taille(y))
return karatsuba(x, y, n // 2)

During your visit to our site, NumWorks needs to install "cookies" or use other technologies to collect data about you in order to:

With the exception of Cookies essential to the operation of the site, NumWorks leaves you the choice: you can accept Cookies for audience measurement by clicking on the "Accept and continue" button, or refuse these Cookies by clicking on the "Continue without accepting" button or by continuing your browsing. You can update your choice at any time by clicking on the link "Manage my cookies" at the bottom of the page. For more information, please consult our cookies policy.