1

I know these kind of questions have already been asked but I'm stuck with this long integer multiplication problem.
for large input size.

import math
import sys

def karatsuba(num1,num2):
    y = 10
    if num1<y or num2<y :
        return num1*num2
    m1 = int(math.log10(num1))+1
    m2 = int(math.log10(num2))+1
    m = max(m1,m2)
    m1 = m/2
    x = y**m1
    high1 = num1//x
    low1 = num1%x
    high2 = num2//x
    low2 = num2%x
    z0 = karatsuba(low1,low2)
    z1 = karatsuba((high1+low1),(high2+low2))
    z2 = karatsuba(high1,high2)
    return((z2*(y**m))+((z1-z2-z0)*x)+z0)



n = int(input())
while n>0:
    n -= 1
    num1,num2 = map(int,input().split())
    print(karatsuba(num1,num2))
ankuselfie
  • 65
  • 1
  • 1
  • 11
  • Why are you calculating `x` like that? `x` can end up substantially greater than either of the inputs. – user2357112 Oct 18 '17 at 21:18
  • Do some basic debugging. Look at high1, low1, hight2, low2 at each step of a test case, for example 123 * 55555. You do not ensure that the next recursive call is a smaller problem. I get the first subproblem z0 = karatsuba(123, 55555) at each step, repeat to infinity. – Kenny Ostrom Oct 18 '17 at 21:32
  • @KennyOstrom I've changed the program and it's working fine with big numbers but still run time error on SPOJ – ankuselfie Oct 18 '17 at 21:37
  • SPOJ? Online judge? Have you tried writing some of your own test cases, like 123 * 55555 (which no longer gives infinite recursion but still gives the wrong answer)? – Kenny Ostrom Oct 18 '17 at 21:41
  • yes. thank you got it :) – ankuselfie Oct 18 '17 at 21:49
  • `thank you got it` You should answer your own question - or delete it. – greybeard Jan 01 '18 at 18:41

0 Answers0