Divide two integers without using multiplication, division and mod operator

14 Jun, 2022
Given a two integers say a and b. Find the quotient after dividing a by b without using multiplication, division and mod operator.
Example: 
Input : a = 10, b = 3
Output : 3

Input : a = 43, b = -8
Output :  -5 
Approach : 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. Below is the implementation of the above approach : 
C++
Java
Python3
C#
PHP
Javascript
// C++ implementation to Divide two// integers without using multiplication,// division and mod operator#include <bits/stdc++.h>using namespace std; // Function to divide a by b and// return floor value of the resultint divide(int dividend, int divisor){     // Calculate sign of divisor i.e.,    // sign will be negative only if    // 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 codeint main(){    int a = 10, b = 3;    cout << divide(a, b) << "\n";     a = 43, b = -8;    cout << divide(a, b);     return 0;}
/*Java implementation to Divide twointegers without using multiplication,division and mod operator*/ import java.io.*; class GFG {     // Function to divide a by b and    // return floor value it    static int divide(int dividend, int divisor)    {         // Calculate sign of divisor i.e.,        // sign will be negative only if        // 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 = Math.abs(dividend);        divisor = Math.abs(divisor);         // Initialize the quotient        int quotient = 0;         while (dividend >= divisor) {            dividend -= divisor;            ++quotient;        }        // if the sign value computed earlier is -1 then        // negate the value of quotient        if (sign == -1)            quotient = -quotient;         return quotient;    }     public static void main(String[] args)    {        int a = 10;        int b = 3;         System.out.println(divide(a, b));         a = 43;        b = -8;         System.out.println(divide(a, b));    }} // This code is contributed by upendra singh bartwal.
# Python 3 implementation to Divide two# integers without using multiplication,# division and mod 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 if    # 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 codea = 10b = 3print(divide(a, b))a = 43b = -8print(divide(a, b)) # This code is contributed by# Smitha Dinesh Semwal
// C# implementation to Divide two without// using multiplication, division and mod// operatorusing System; class GFG {     // Function to divide a by b and    // return floor value it    static int divide(int dividend, int divisor)    {         // Calculate sign of divisor i.e.,        // sign will be negative only if        // 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 = Math.Abs(dividend);        divisor = Math.Abs(divisor);         // Initialize the quotient        int quotient = 0;         while (dividend >= divisor) {            dividend -= divisor;            ++quotient;        }         // if the sign value computed earlier is -1 then        // negate the value of quotient        if (sign == -1)            quotient = -quotient;        return quotient;    }     public static void Main()    {         int a = 10;        int b = 3;        Console.WriteLine(divide(a, b));         a = 43;        b = -8;        Console.WriteLine(divide(a, b));    }} // This code is contributed by vt_m.
<?php// PHP implementation to Divide two// integers without using multiplication,// division and mod operator // Function to divide a by b and// return floor value itfunction divide($dividend, $divisor) {     // Calculate sign of divisor i.e.,    // sign will be negative only if    // either one of them is negative    // otherwise it will be positive    $sign = (($dividend < 0) ^             ($divisor < 0)) ? -1 : 1;         // Update both divisor and    // dividend positive    $dividend = abs($dividend);    $divisor = abs($divisor);         // Initialize the quotient    $quotient = 0;    while ($dividend >= $divisor)    {        $dividend -= $divisor;        ++$quotient;    }    //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;echo divide($a, $b)."\n"; $a = 43;$b = -8;echo divide($a, $b); // This code is contributed by Sam007?>
<script> // Javascript implementation to Divide two// integers without using multiplication,// division and mod operator // Function to divide a by b and// return floor value itfunction divide(dividend, divisor) { // Calculate sign of divisor i.e.,// sign will be negative only if// either one of them is negative// otherwise it will be positivelet sign = ((dividend < 0) ^ (divisor < 0)) ? -1 : 1; // Update both divisor and// dividend positivedividend = Math.abs(dividend);divisor = Math.abs(divisor); // Initialize the quotientlet quotient = 0;while (dividend >= divisor) {    dividend -= divisor;    ++quotient;}//if the sign value computed earlier is -1 then negate the value of quotientif(sign==-1) quotient=-quotient;return quotient;} // Driver codelet a = 10, b = 3;document.write(divide(a, b) + "<br>"); a = 43, b = -8;document.write(divide(a, b)); // This code is contributed by Surbhi Tyagi. </script>
3
-5
Time complexity : O(a/b) Auxiliary space : O(1)Efficient Approach: Use bit manipulation in order to find the quotient. The divisor and dividend can be written as 
dividend = quotient * divisor + remainder
As every number can be represented in base 2(0 or 1), represent the quotient in binary form by using the shift operator as given below : 
Determine the most significant bit in the divisor. This can easily be calculated by iterating on the bit position i from 31 to 1.Find the first bit for which divisor << i is less than dividend and keep updating the ith bit position for which it is true.Add the result in the temp variable for checking the next position such that (temp + (divisor << i) ) is less than the dividend.Return the final answer of the quotient after updating with a corresponding sign.
Determine the most significant bit in the divisor. This can easily be calculated by iterating on the bit position i from 31 to 1.
Find the first bit for which divisor << i is less than dividend and keep updating the ith bit position for which it is true.
Add the result in the temp variable for checking the next position such that (temp + (divisor << i) ) is less than the dividend.
Return the final answer of the quotient after updating with a corresponding sign.
Below is the implementation of the above approach :  
C++
Java
Python3
C#
PHP
Javascript
// C++ implementation to Divide two// integers without using multiplication,// division and mod operator#include <bits/stdc++.h>using namespace std; // Function to divide a by b and// return floor value itint divide(long long dividend, long long divisor) {   // Calculate sign of divisor i.e.,  // sign will be negative only if  // either one of them is negative  // otherwise it will be positive  int sign = ((dividend < 0) ^              (divisor < 0)) ? -1 : 1;   // remove sign of operands  dividend = abs(dividend);  divisor = abs(divisor);   // Initialize the quotient  long long quotient = 0, temp = 0;   // test down from the highest bit and  // accumulate the tentative value for  // valid bit  for (int i = 31; i >= 0; --i) {     if (temp + (divisor << i) <= dividend) {      temp += divisor << i;      quotient |= 1LL << i;    }  }  //if the sign value computed earlier is -1 then negate the value of quotient  if(sign==-1) quotient=-quotient;     return quotient;} // Driver codeint main() {  int a = 10, b = 3;  cout << divide(a, b) << "\n";   a = 43, b = -8;  cout << divide(a, b);   return 0;}
// Java implementation to Divide// two integers without using// multiplication, division// and mod operatorimport java.io.*;import java.util.*; // Function to divide a by b// and return floor value itclass GFG{public static long divide(long dividend,                        long divisor){ // Calculate sign of divisor// i.e., sign will be negative// only if either one of them// is negative otherwise it// will be positivelong sign = ((dividend < 0) ^            (divisor < 0)) ? -1 : 1; // remove sign of operandsdividend = Math.abs(dividend);divisor = Math.abs(divisor); // Initialize the quotientlong quotient = 0, temp = 0; // test down from the highest// bit and accumulate the// tentative value for// valid bit// 1<<31 behaves incorrectly and gives Integer// Min Value which should not be the case, instead  // 1L<<31 works correctly.for (int i = 31; i >= 0; --i){     if (temp + (divisor << i) <= dividend)    {        temp += divisor << i;        quotient |= 1L << i;    }} //if the sign value computed earlier is -1 then negate the value of quotientif(sign==-1)  quotient=-quotient;return quotient;} // Driver codepublic static void main(String args[]){int a = 10, b = 3;System.out.println(divide(a, b)); int a1 = 43, b1 = -8;System.out.println(divide(a1, b1));  }} // This code is contributed// by Akanksha Rai(Abby_akku)
# Python3 implementation to# Divide two integers# without using multiplication,# division and mod operator # Function to divide a by# b and return floor value itdef divide(dividend, divisor):         # Calculate sign of divisor    # i.e., sign will be negative    # either one of them is negative    # only if otherwise it will be    # positive         sign = (-1 if((dividend < 0) ^                  (divisor < 0)) else 1);         # remove sign of operands    dividend = abs(dividend);    divisor = abs(divisor);         # Initialize    # the quotient    quotient = 0;    temp = 0;         # test down from the highest    # bit and accumulate the    # tentative value for valid bit    for i in range(31, -1, -1):        if (temp + (divisor << i) <= dividend):            temp += divisor << i;            quotient |= 1 << i;    #if the sign value computed earlier is -1 then negate the value of quotient    if sign ==-1 :      quotient=-quotient;    return quotient; # Driver codea = 10;b = 3;print(divide(a, b)); a = 43;b = -8;print(divide(a, b)); # This code is contributed by mits
// C# implementation to Divide// two integers without using// multiplication, division// and mod operatorusing System; // Function to divide a by b// and return floor value itclass GFG{public static long divide(long dividend,                          long divisor){ // Calculate sign of divisor// i.e., sign will be negative// only if either one of them// is negative otherwise it// will be positivelong sign = ((dividend < 0) ^             (divisor < 0)) ? -1 : 1; // remove sign of operandsdividend = Math.Abs(dividend);divisor = Math.Abs(divisor); // Initialize the quotientlong quotient = 0, temp = 0; // test down from the highest// bit and accumulate the// tentative value for// valid bitfor (int i = 31; i >= 0; --i){     if (temp + (divisor << i) <= dividend)    {        temp += divisor << i;        quotient |= 1LL << i;    }}//if the sign value computed earlier is -1 then negate the value of quotient  if(sign==-1)    quotient=-quotient;return quotient;} // Driver codepublic static void Main(){int a = 10, b = 3;Console.WriteLine(divide(a, b)); int a1 = 43, b1 = -8;Console.WriteLine(divide(a1, b1)); }} // This code is contributed by mits
<?php// PHP implementation to// Divide two integers// without using multiplication,// division and mod operator // Function to divide a by// b and return floor value itfunction divide($dividend,                $divisor){ // Calculate sign of divisor// i.e., sign will be negative// either one of them is negative// only if otherwise it will be// positive$sign = (($dividend < 0) ^         ($divisor < 0)) ? -1 : 1; // remove sign of operands$dividend = abs($dividend);$divisor = abs($divisor); // Initialize// the quotient$quotient = 0;$temp = 0; // test down from the highest// bit and accumulate the// tentative value for valid bitfor ($i = 31; $i >= 0; --$i){     if ($temp + ($divisor << $i) <= $dividend)    {        $temp += $divisor << $i;        $quotient |= (double)(1) << $i;    }}//if the sign value computed earlier is -1 then negate the value of quotientif($sign==-1)  $quotient=-$quotient;return $quotient;} // Driver code$a = 10;$b = 3;echo divide($a, $b). "\n"; $a = 43;$b = -8;echo divide($a, $b); // This code is contributed by mits?>
<script> // JavaScript implementation to Divide// two integers without using// multiplication, division// and mod operator // Function to divide a by b// and return floor value it function divide(dividend, divisor){ // Calculate sign of divisor// i.e., sign will be negative// only if either one of them// is negative otherwise it// will be positivevar sign = ((dividend < 0)?1:0 ^             (divisor < 0)?1:0) ? -1 : 1; // remove sign of operandsdividend = Math.abs(dividend);divisor = Math.abs(divisor); // Initialize the quotientvar quotient = 0, temp = 0; // test down from the highest// bit and accumulate the// tentative value for// valid bitwhile (dividend >= divisor) {    dividend -= divisor;    ++quotient;}//if the sign value computed earlier is -1 then negate the value of quotientif(sign==-1) quotient=-quotient;return quotient;} // Driver code var a = 10, b = 3;document.write(divide(a, b) + "<br>"); var a1 = 43, b1 = -8;document.write(divide(a1, b1) + "<br>");   </script>
3
-5
Time complexity : O(log(a)) Auxiliary space : O(1)
Sam007
Mithun Kumar
Akanksha_Rai
ajit2994
nirajkumar123580
abhishekagc966
ujjwalmittal
surbhityagi15
rutvik_56
shetgaonkarashwin18
akhilkashyap
akashdeep8
vaibhavimandloi
surinderdawra388
SristiJain1
simmytarika5
kingrishabdugar
Bit Magic
Bit Magic
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Little and Big Endian Mystery
Bits manipulation (Important tactics)
Josephus problem | Set 1 (A O(n) Solution)
Bit Fields in C
C++ bitset and its application
Find the element that appears once
Add two numbers without using arithmetic operators
Set, Clear and Toggle a given bit of a number in C
Cyclic Redundancy Check and Modulo-2 Division
Count total set bits in all numbers from 1 to n