Write a function subtract(x, y) that returns x-y where x and y are integers. The function should not use any of the arithmetic operators (+, ++, –, -, … etc).
The idea is to use bitwise operators. Like addition, Write a function Add() that returns sum of two integers. The function should not use any of the arithmetic operators (+, ++, –, -, … etc). Sum of two bits can be obtained by performing XOR (^) of the two bits. Carry bit can be obtained by performing AND (&) of two bits. We can extend this logic for integers. If x and y don’t have set bits at same position(s), then bitwise XOR (^) of x and y gives the sum of x and y. To incorporate common set bits also, bitwise AND (&) is used. Bitwise AND of x and y gives all carry bits. We calculate (x & y) << 1 and add it to x ^ y to get the required result. The idea is to use subtractor logic.
The truth table for the half subtractor is given below.
X Y Diff Borrow
0 0 0 0
0 1 1 1
1 0 1 0
1 1 0 0
From the above table one can draw the Karnaugh map for “difference” and “borrow”.
So, Logic equations are:
Diff = y ⊕ x
Borrow = x' . y
Following is recursive implementation for the same approach.
<?php
function subtract( $x , $y )
{
if ( $y == 0)
return $x ;
return subtract( $x ^ $y ,
(~ $x & $y ) << 1);
}
// Driver Code
$x = 29; $y = 13;
echo "x - y is " , subtract( $x , $y );
?>
Output :
x - y is 16