How to divide two integers without using the division operator ('/') in C++

1 Answer

0 votes
#include <iostream>
#include <cmath>        // for abs()

// Function that performs integer division without using '/'
int divide(int dividend, int divisor) {
    // Handle division by zero
    if (divisor == 0) {
        std::cerr << "Error: division by zero!" << std::endl;
        return 0;
    }

    // Determine the sign of the result
    bool negative = (dividend < 0) ^ (divisor < 0);

    // Work with positive values for the algorithm
    long long a = std::llabs(dividend);
    long long b = std::llabs(divisor);

    long long result = 0;

    // Efficient division using bit shifting
    // We repeatedly subtract the largest shifted divisor from the dividend
    while (a >= b) {
        long long temp = b;
        long long multiple = 1;

        // Shift divisor left until it is just below dividend
        while ((temp << 1) <= a) {
            temp <<= 1;       // multiply by 2
            multiple <<= 1;   // track how many times we multiplied
        }

        // Subtract the largest chunk found
        a -= temp;
        result += multiple;
    }

    // Apply sign
    return negative ? -result : result;
}

int main() {
    int x = 37;
    int y = 5;

    int result = divide(x, y);

    std::cout << "Result of " << x << " / " << y << " = " << result << std::endl;
}


/*
run:

Result of 37 / 5 = 7

*/

 



answered 1 day ago by avibootz
...