Advertisement
Eternoseeker

Ch-Assignment1-Karatsuba

Nov 24th, 2023
368
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.59 KB | Source Code | 0 0
  1. def square(x,y):
  2.     if x<10 or y<10:
  3.         return x*y
  4.    
  5.     strx,stry = str(x),str(y)
  6.     n = max(len(strx) , len(stry))
  7.     # Calculate Half Length
  8.     half_len = (n+1)//2
  9.    
  10.     # a is first half of x, b is second half of x
  11.     a,b = int(strx[:-half_len] or '0') , int(strx[-half_len:])
  12.     c,d = int(stry[:-half_len] or '0') , int(stry[-half_len:])
  13.  
  14.     C0 = square(b , d)
  15.     C1 = square((a + b) , (c + d))
  16.     C2 = square(a, c)
  17.    
  18.     return (C2*10**(2*half_len)) + ((C1-C2-C0)**10*half_len) + C0
  19.    
  20. n = 90827103459082710345
  21. print("Square of 20 digit Number:",square(n,n))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement