top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

C: How to divide two integers without using multiplication, division and mod operator?

+2 votes
458 views
C: How to divide two integers without using multiplication, division and mod operator?
posted Oct 5, 2015 by anonymous

Share this question
Facebook Share Button Twitter Share Button LinkedIn Share Button

1 Answer

0 votes

Try the following

int divide(int dividend, int divisor) {
    int sign = 1;
    unsigned long long tmp = abs((long long)dividend);
    unsigned long long tmp2 = abs((long long)divisor);                
    unsigned long c = 1;
    int res = 0;

    if (dividend<0){sign = -sign;}
    if (divisor<0){sign = -sign;}

    while (tmp>tmp2){
        tmp2 = tmp2<<1;    
        c = c<<1;
    }

    while (tmp>=abs((long long)divisor)){
        while (tmp>=tmp2){
            tmp -= tmp2;
            res = res+c;
        }
        tmp2=tmp2>>1;
        c=c>>1;    
    }

    return sign*res;
}

Logic:
1. Keep multiply 2 (<<1) to the divisor, until it is greater than the dividend. Store the times of shift operation.
2. if dividend > divisor, then dividend = dividend - divisor/2(>>1). Until dividend< original divisor. Store the result.
3. Output the result.

answer Oct 5, 2015 by Salil Agrawal
Similar Questions
0 votes

You are given 2 long integers having n digits each and you are required to multiply them using C.

Assumptions
Numbers are represented in an array of size n .
Calculate the time complexity using traditional divide and conquer

+2 votes

How can I wwap value two variables without using third variable or +/- operator?

...