Divide two integers without using multiplication , division and mod operator | C ++ implementation to Divide two integers without using multiplication , division and mod operator ; Function to divide a by b and return floor value it ; Calculate sign of divisor i . e . , sign will be negative only iff either one of them is negative otherwise it will be positive ; remove sign of operands ; Initialize the quotient ; test down from the highest bit and accumulate the tentative value for valid bit ; if the sign value computed earlier is - 1 then negate the value of quotient ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int divide ( long long dividend , long long divisor ) { int sign = ( ( dividend < 0 ) ^ ( divisor < 0 ) ) ? -1 : 1 ; dividend = abs ( dividend ) ; divisor = abs ( divisor ) ; long long quotient = 0 , temp = 0 ; for ( int i = 31 ; i >= 0 ; -- i ) { if ( temp + ( divisor << i ) <= dividend ) { temp += divisor << i ; quotient |= 1LL << i ; } } if ( sign == -1 ) quotient = - quotient ; return quotient ; } int main ( ) { int a = 10 , b = 3 ; cout << divide ( a , b ) << " STRNEWLINE " ; a = 43 , b = -8 ; cout << divide ( a , b ) ; return 0 ; }