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 implementation based on above equations.
// C program to Subtract two numbers
// without using arithmetic operators
#include<stdio.h>
int
subtract(
int
x,
int
y)
{
// Iterate till there
// is no carry
while
(y != 0)
{
// borrow contains common
// set bits of y and unset
// bits of x
int
borrow = (~x) & y;
// Subtraction of bits of x
// and y where at least one
// of the bits is not set
x = x ^ y;
// Borrow is shifted by one
// so that subtracting it from
// x gives the required sum
y = borrow << 1;
}
return
x;
}
// Driver Code
int
main()
{
int
x = 29, y = 13;
printf
(
"x - y is %d"
, subtract(x, y));
return
0;
}
Output :
x - y is 16