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 either one of them is negative only iff 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
def divide ( dividend , divisor ) : NEW_LINE INDENT sign = ( - 1 if ( ( dividend < 0 ) ^ ( divisor < 0 ) ) else 1 ) ; NEW_LINE dividend = abs ( dividend ) ; NEW_LINE divisor = abs ( divisor ) ; NEW_LINE quotient = 0 ; NEW_LINE temp = 0 ; NEW_LINE for i in range ( 31 , - 1 , - 1 ) : NEW_LINE INDENT if ( temp + ( divisor << i ) <= dividend ) : NEW_LINE INDENT temp += divisor << i ; NEW_LINE quotient |= 1 << i ; NEW_LINE DEDENT DEDENT if sign == - 1 : NEW_LINE quotient = - quotient ; NEW_LINE return quotient ; NEW_LINE DEDENT a = 10 ; NEW_LINE b = 3 ; NEW_LINE print ( divide ( a , b ) ) ; NEW_LINE a = 43 ; NEW_LINE b = - 8 ; NEW_LINE print ( divide ( a , b ) ) ; NEW_LINE