-1

I'm trying to implement Karatsuba multiplication through recursive calls. The code below should work, but I keep getting the Zero as answer. Any thoughts?

#define ll long long int 
ll  kmul(ll p, ll q)
{
   ll a,b,c,d,ans;
   ll n=0;
   while(p)
   {
      p=p/10;
      n++;
   }
   //cout<<n<<endl;
  if(n<2)
  {
      return p*q;
  }
  else
  {
     int k=n/2;
     ll j=pow(10,k);
     a=p/j;
     b=p%j;
     c=q/(j);
     b=q%j;
     ans=(pow(10,n)*(kmul(a,c)))+(j*kmul(a,d)*kmul(b,c))+kmul(b,d);
     return ans;
  }
 } 
  • 2
    That `#define` is really, really needless. – Daniel Kamil Kozar Oct 23 '16 at 17:50
  • Have you tried using a debugger? – UnholySheep Oct 23 '16 at 17:50
  • 1
    The right tool to solve such problems is your debugger. You should step through your code line-by-line *before* asking on Stack Overflow. For more help, please read [How to debug small programs (by Eric Lippert)](https://ericlippert.com/2014/03/05/how-to-debug-small-programs/). At a minimum, you should \[edit] your question to include a [Minimal, Complete, and Verifiable](http://stackoverflow.com/help/mcve) example that reproduces your problem, along with the observations you made in the debugger. – πάντα ῥεῖ Oct 23 '16 at 17:51
  • Could you be bothered to (enlighteningly/insightfully) comment that code? – greybeard Oct 23 '16 at 17:51
  • thankyou everyone. i will keep that in mind – Aishwarya Bhave Oct 23 '16 at 18:02

2 Answers2

1

After this loop:

while(p)
{
  p=p/10;
  n++;
}

The value of p is zero. Your recursion stops at

if(n<2)
{
  return p*q;
}

Thus, no matter what is the input, you get zero as result.

463035818_is_not_an_ai
  • 109,796
  • 11
  • 89
  • 185
0

You might wanna use a copy of p for calculating n in the while loop. That way you can preserve the value of p. Something like this:

ll pd = p;
while(pd)
{
  pd=pd/10;
  n++;
}
officialaimm
  • 378
  • 4
  • 16