Divide Integers without Division Arithmetic Operator in Python
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 Python.
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 Python
Python Program To Divide Integers Without Division Arithmetic Operator
a = 10, b = 33
# Python implementation to Divide two # integers without using division operator # Function to divide a by b and # return floor value it def divide(dividend, divisor): # Calculate sign of divisor i.e., # sign will be negative only iff # either one of them is negative # otherwise it will be positive sign = -1 if ((dividend < 0) ^ (divisor < 0)) else 1 # Update both divisor and # dividend positive dividend = abs(dividend) divisor = abs(divisor) # Initialize the quotient quotient = 0 while (dividend >= divisor): dividend -= divisor quotient += 1 #if the sign value computed earlier is -1 then negate the value of quotient if sign ==-1: quotient=-quotient return quotient # Driver code a = 10 b = 3 print(divide(a, b))