nomorequestions nomorequestions - 2 months ago 10
C Question

dividing a number without using division operator in c

How can I divide a number with an unknown number without using these operators

('*', '/', '%')
. Denominator is given during runtime.

Answer

You can use this function

int divide(int nu, int de) {

    int temp = 1;
    int quotient = 0;

    while (de <= nu) {
        de <<= 1;
        temp <<= 1;
    }

    //printf("%d %d\n",de,temp,nu);
    while (temp > 1) {
        de >>= 1;
        temp >>= 1;

        if (nu >= de) {
            nu -= de;
            //printf("%d %d\n",quotient,temp);
            quotient += temp;
        }
    }

    return quotient;
}

You can pass a numerator and a denominator to this function and get the required quotient.

Comments