VOOZH about

URL: https://www.geeksforgeeks.org/dsa/divide-two-integers-without-using-multiplication-division-mod-operator/

⇱ Divide two integers without using multiplication and division operator - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Divide two integers without using multiplication and division operator

Last Updated : 19 Sep, 2024

Given two integers a and b, the task is to find the quotient after dividing a by b without using multiplication, division, and mod operator.

Note: If the quotient is strictly greater than 231 - 1, return 231 - 1 and if the quotient is strictly less than -231, then return -231.

Examples:

Input : a = 10, b = 3
Output : 3

Input: a = 43, b = -8
Output:  -5 

[Naive Approach] By Repeated Subtraction - O(a/b) Time and O(1) Space

The basic idea is to first find the sign of quotient. The sign of the quotient will be negative only when the sign of dividend and divisor are different. Now, convert both the dividend and divisor to positive numbers and keep subtracting the divisor from the dividend until the dividend becomes less than the divisor. The dividend becomes the remainder, and the number of times subtraction is done becomes the quotient. Finally, we append the sign to the quotient to get the final result.

This approach fails for large values of quotient.


Output
-5

Time complexity: O(a/b), where a is the dividend and b is the divisor.
Auxiliary space: O(1)

[Expected Approach] Using Bit Manipulation - O(log(a)) Time and O(1) Space

The idea is similar to the previous approach with the only difference that instead of subtracting one unit of divisor from the dividend, we can subtract multiple units of divisor at once until the dividend becomes smaller than divisor.

👁 Division-without-using-operators
Division without using multiplication and division operator

This can be easily done by iterating on the bit position i = 30 to 0. For each bit position i, where (divisor << i) is less than dividend, set the ith bit of the quotient and subtract (divisor << i) from the dividend. After iterating over all the bits, return the quotient with the corresponding sign.


Output
-5

Time Complexity: O(log(a)), as we are iterating over all the bits of a.
Auxiliary Space: O(1)

Comment
Article Tags:
Article Tags: