Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,885 questions

51,811 answers

573 users

How to divide two integers without using multiplication, division, and mod operator in C++

1 Answer

0 votes
#include <iostream>
#include <limits.h>

int divide(int dividend, int divisor) {
    // Handle edge cases
    if (divisor == 0) {
        throw std::invalid_argument("Divisor cannot be zero.");
    }
    if (dividend == INT_MIN && divisor == -1) {
        return INT_MAX; // Overflow case
    }

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

    // Convert both numbers to positive
    long long absDividend = std::abs(static_cast<long long>(dividend));
    long long absDivisor = std::abs(static_cast<long long>(divisor));

    int result = 0;

    // Perform the division using bit manipulation
    while (absDividend >= absDivisor) {
        long long temp = absDivisor, multiple = 1;
        while (absDividend >= (temp << 1)) {
            temp <<= 1;
            multiple <<= 1;
        }
        absDividend -= temp;
        result += multiple;
    }

    return negative ? -result : result;
}

int main() {
    int dividend = 42;
    int divisor = 6;
    
    try {
        int result = divide(dividend, divisor);
        std::cout << "Result: " << result << std::endl;
    } catch (const std::invalid_argument& e) {
        std::cerr << e.what() << std::endl;
    }
}



/*
run:

Result: 7

*/

 



answered May 4, 2025 by avibootz
...