1,225 views
0 votes
0 votes
Write a function (proper programming code) for multiplying two integers without using '*' operator and considering all corner cases.

2 Answers

2 votes
2 votes

One of possible case for multiplying two integers without using '*' operator.
Case:1 Recursively add x y time.
int mul(int x, int y)
{

if(y == 0 || x==0)
    return 0;

if(y > 0 )
    return (x + mul(x, y-1));

if(y < 0 )
    return mul(-x, -y);
}

Time complexity of above function is O(y).

case 2:swap x and y if x is lower than y.

int mul(int x,int y,int mult){
    if(y==0)
    return mult;

    if(y<0){
        x=-x;
        y=-y;
    }
    return mul(x,y-1,mult+x);
}

Case 3:We have alternative which is optimal.

mul(x,y)
{
if(x==0||y==0)
return 0;
if (y == 1)
return x;
if (y % 2 == 0)
return mul(x + x, y >> 1);
else
return x + mul(x + x, y >> 1);
}

Time complexity of this function is O(log(y)).

edited by
0 votes
0 votes
let two numbers be a and b

mul(a,b)={ 0   if b=0

                a+mul(a,b-1)   if b>0

                   mul(-a,-b) if b<0

Related questions

2 votes
2 votes
2 answers
1
Arjun asked Jul 3, 2016
2,977 views
Given an array of $n$ elements find the maximum continuous sum in it. For example consider the below array of $n=6$.23 4 -10 2 15 1Answer is 35.
1 votes
1 votes
0 answers
2
Arjun asked Jun 6, 2016
449 views
Write an object oriented code for representing boolean expressions and then a function for checking the equivalence of two boolean expressions.
0 votes
0 votes
0 answers
3
Arjun asked Jun 6, 2016
1,053 views
Given an arithmetic expression involving *, + only write an object oriented code for its representation and evaluation
1 votes
1 votes
4 answers
4
Arjun asked Jun 6, 2016
1,944 views
Given an input string of length $n$, find the maximum length of the substring containing maximum $k$ unique characters. For example, for "abbcdaadcd" and $k=2$ answer wil...