How is this code correct for negative integers?


i have written the multiplication function using recursion
but i am not able to understand that how is this code giving the correct solution even for negative ‘b’ ?

@alankrit.agr99
While the code works for negative values as well , that is not at all optimised. Instead add this base condition,
if( b < 0 )
return - mul ( a, -b ) ;

Your code simply worked for the negative values as there were so many repeated recursive calls that the value exceeded INT_MAX and overflowed and then we started again with the negative numbers. Your code requires a lot of time and might even still give some wrong answers in some cases.

I hope I’ve cleared your doubt. I ask you to please rate your experience here
Your feedback is very important. It helps us improve our platform and hence provide you
the learning experience you deserve.

On the off chance, you still have some questions or not find the answers satisfactory, you may reopen
the doubt.