Divide Integers without Division Arithmetic Operator in C++
Confronting with numbers is the first thing each one of us has learned in school. However, as we step up high more and more difficult questions based on the same fundamentals seem to appear in our way. It’s the same with programming, using the same fundamentals to find solutions for multiple complex problems. Now the cool thing is, you can be creative in your way eventually coming up with a unique solution. And if you’re able to do this, then you’ve clearly understood how to use programming for others and your good. But keeping that aside, we’ve talked about numbers before. So what if we do simple division, seems too easy right!. Well, it doesn’t cause we’re not going to use the division Arithmetic Operator when writing this program. So let’s quickly find out how to Divide Integers without Division Arithmetic operator in C++.
With the help of this program, you will be able to find the division of two integers without using the divide Arithmetic Operator. Practicing these types of questions also helps to get an upper edge in Competitive Programming.
What’s The Approach?
- The basic approach we’re going to follow for division is subtraction.
- We will subtract the dividend from the divisor until the dividend becomes less than the divisor itself.
- By the above instruction, the dividend becomes the remainder. And the number of times subtraction has taken place becomes the quotient.
Also Read: Swap Integers Without Temporary Variable in C++
C++ Program To Divide Integers Without Division Arithmetic Operator
Input:
a = 10, b = 33
Output:
3
// C++ implementation to Divide two // integers without using division operator #include <bits/stdc++.h> using namespace std; // Function to divide a by b and // return floor value it int divide(int dividend, int divisor) { // Calculate sign of divisor i.e., // sign will be negative only iff // either one of them is negative // otherwise it will be positive int sign = ((dividend < 0) ^ (divisor < 0)) ? -1 : 1; // Update both divisor and // dividend positive dividend = abs(dividend); divisor = abs(divisor); // Initialize the quotient int quotient = 0; while (dividend >= divisor) { dividend -= divisor; ++quotient; } // Return the value of quotient with the appropriate sign. return quotient * sign; } // Driver code int main() { int a = 10, b = 3; cout << divide(a, b) << "\n"; return 0; }