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
< ? php function divide ( $ dividend , $ divisor ) { $ sign = ( ( $ dividend < 0 ) ^ ( $ divisor < 0 ) ) ? -1 : 1 ; $ dividend = abs ( $ dividend ) ; $ divisor = abs ( $ divisor ) ; $ quotient = 0 ; $ temp = 0 ; for ( $ i = 31 ; $ i >= 0 ; -- $ i ) { if ( $ temp + ( $ divisor << $ i ) <= $ dividend ) { $ temp += $ divisor << $ i ; $ quotient |= ( double ) ( 1 ) << $ i ; } } if ( $ sign == -1 ) $ quotient = - $ quotient ; return $ quotient ; } $ a = 10 ; $ b = 3 ; echo divide ( $ a , $ b ) . " STRNEWLINE " ; $ a = 43 ; $ b = -8 ; echo divide ( $ a , $ b ) ; ? >