Here's all the functions in C that does all the arithmetic operators without using arithmetic operators themselves, mostly using bitwise operators. Recursive functions and comparison operators are also allowed.
int add ( int augend, int addend )
{
return addend ? add ( augend ^ addend, ( augend & addend ) << 1 ) : augend;
}
int subtract ( int minuend, int subtrahend )
{
return add ( minuend, add ( ~subtrahend, 1 ) );
}
int multiply_recursive ( int multiplicand, int multiplier, int product )
{
if ( !multiplier ) return product;
if ( multiplier & 1 ) product = add ( multiplicand, product );
return multiply_recursive ( multiplicand << 1, (int)( (unsigned) multiplier >> 1 ),
product );
}
int multiply ( int multiplicand, int multiplier )
{
return multiply_recursive ( multiplicand, multiplier, 0 );
}
int divide_recursive ( int dividend, int divisor, int size, int quotient, int remainder )
{
if ( !size ) return quotient;
int position = subtract ( size, 1 );
remainder <<= 1;
remainder |= ( dividend >> position ) & 1;
if ( remainder >= divisor ) {
remainder = subtract ( remainder, divisor );
quotient |= 1 << position;
}
return divide_recursive ( dividend, divisor, position, quotient, remainder );
}
int abs ( int integer )
{
int const mask = integer >> subtract ( multiply ( sizeof(int), 8 ), 1 );
return add ( integer, mask ) ^ mask;
}
int divide ( int dividend, int divisor )
{
int quotient = divide_recursive ( abs ( dividend ), abs ( divisor ),
multiply ( sizeof(int), 8 ), 0, 0 );
return ( dividend ^ divisor ) < 0 ? add ( ~quotient, 1 ) : quotient;
}
int mod ( int dividend, int divisor )
{
return subtract ( dividend, multiply ( divide ( dividend, divisor ), divisor ) );
}