C Sharp Program to subtract 2 numbers without using arithmetic operators.

Subtract 2 numbers without using arithmetic operators – Learn how to subtract 1 from a given input number and also learn how to subtract 2 given input numbers with example programs.

To subtract 1 from a number x, set all the the bits to 1 after the rightmost 1 bit.
finally unset the right most bit to get the answer.

x=6
x=00110 in binary

here right most 1 bit is in second position.
set all the bits to 1 after rightmost  1 bit(second position bit) , then binary string is 00111.
finally unset the right most bit 1(second position ) to zero.
00101

Program to subtract one from a given number.

c# code

using System;
    class Program
    {
        static void Main(string[] args)
        {
            int x = 6;
            int y = 1;
            int Num1=x,Num2=y;
             //set all the bits to 1 after the right most 1 bit.
 
            while(!((x&y)>0))
            {
                x = x ^ y;
                y = y << 1;
            }
           //unset the right most 1 bit zero

            x = x ^ y;
            Console.WriteLine("subtract {0}- {1} = {2}" ,Num1,Num2,x);
        }
    }

Output

subtract 6- 1 = 5

We can subtract 2 numbers using half sub-tractor logic.

Half subs-tractor
diff=x^y
borrow=(~x).y

The below program is based on the above formulas.

Program to subtract 2 numbers without using arithmetic operators.

c# code

using System;
class Program
    {
        static void Main()
        {
            int y = 10;
            int x = 21;
            int Num1=x,Num2=y;
            int borrow = 0;
              //loop till there is no carry
            while (y != 0)
            {
                //borrow contains set bits of y and unset bits of x
                borrow = (~x) & y;
                //subtraction of bits of x and y where atleast one of the bits not set
                x = x ^ y;
                //borrow is shifted by one 
                //so that subtracting it from 
                //x gives the required sum

                y = borrow << 1;
            }
            Console.WriteLine("subtract {0}- {1} =  {2}" ,Num1,Num2,x);
        }
    }

Output

subtract 21- 10 = 11

Related Posts