Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Practice Bitwise Algorithms
  • MCQs on Bitwise Algorithms
  • Tutorial on Biwise Algorithms
  • Binary Representation
  • Bitwise Operators
  • Bit Swapping
  • Bit Manipulation
  • Count Set bits
  • Setting a Bit
  • Clear a Bit
  • Toggling a Bit
  • Left & Right Shift
  • Gray Code
  • Checking Power of 2
  • Important Tactics
  • Bit Manipulation for CP
  • Fast Exponentiation
Open In App
Next Article:
To find sum of two numbers without using any operator
Next article icon

Subtract two numbers without using arithmetic operators

Last Updated : 01 Nov, 2021
Comments
Improve
Suggest changes
Like Article
Like
Report

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. Addition of two numbers has been discussed using Bitwise operators. Like addition, 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 

Source: Wikipedia page for subtractor

Following is implementation based on above equations.  

C++




// C++ program to Subtract two numbers
// without using arithmetic operators
#include <iostream>
using namespace std;
 
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;
    cout << "x - y is " << subtract(x, y);
    return 0;
}
 
// This code is contributed by shivanisinghss2110
 
 

C




// 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;
}
 
 

Java




// Java Program to subtract two Number
// without using arithmetic operator
import java.io.*;
 
class GFG
{
    static 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
    public static void main (String[] args)
    {
        int x = 29, y = 13;
         
        System.out.println("x - y is " +
                        subtract(x, y));
    }
}
 
// This code is contributed by vt_m
 
 

Python3




def subtract(x, y):
 
    # Iterate till there
    # is no carry
    while (y != 0):
     
        # borrow contains common
        # set bits of y and unset
        # bits of x
        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
x = 29
y = 13
print("x - y is",subtract(x, y))
 
# This code is contributed by
# Smitha Dinesh Semwal
 
 

C#




// C# Program to subtract two Number
// without using arithmetic operator
using System;
 
class GFG {
     
    static 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
    public static void Main ()
    {
        int x = 29, y = 13;
         
        Console.WriteLine("x - y is " +
                        subtract(x, y));
    }
}
 
// This code is contributed by anuj_67.
 
 

PHP




<?php
// PHP Program to subtract two Number
// without using arithmetic operator
 
function subtract($x, $y)
{
     
    // Iterate till there is no carry
    while ($y != 0)
    {
         
        // borrow contains common set
        // bits of y and unset
        // bits of x
        $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
        $x = 29; $y = 13;
        echo "x - y is ", subtract($x,$y);
 
// This code is contributed by Ajit
?>
 
 

Javascript




<script>
 
// JavaScript program to Subtract two numbers
// without using arithmetic operators
 
function subtract(x, y)
{
    // Iterate till there
    // is no carry
    while (y != 0)
    {
        // borrow contains common
        // set bits of y and unset
        // bits of x
        let 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
  
let x = 29, y = 13;
document.write("x - y is " + subtract(x, y));
 
 
// This code is contributed by Surbhi Tyagi.
 
</script>
 
 

Output : 

x - y is 16

Time Complexity: O(log y)

Auxiliary Space: O(1)

Following is recursive implementation for the same approach. 

C++




#include <iostream>
using namespace std;
 
int subtract(int x, int y)
{
    if (y == 0)
        return x;
    return subtract(x ^ y, (~x & y) << 1);
}
 
// Driver program
int main()
{
    int x = 29, y = 13;
    cout << "x - y is "<< subtract(x, y);
    return 0;
}
 
// this code is contributed by shivanisinghss2110
 
 

C




#include<stdio.h>
 
int subtract(int x, int y)
{
    if (y == 0)
        return x;
    return subtract(x ^ y, (~x & y) << 1);
}
 
// Driver program
int main()
{
    int x = 29, y = 13;
    printf("x - y is %d", subtract(x, y));
    return 0;
}
 
 

Java




// Java  Program to subtract two Number
// without using arithmetic operator
// Recursive implementation.
class GFG {
 
    static int subtract(int x, int y)
    {
 
        if (y == 0)
            return x;
 
        return subtract(x ^ y, (~x & y) << 1);
    }
 
    // Driver program
    public static void main(String[] args)
    {
        int x = 29, y = 13;
        System.out.printf("x - y is %d",
                            subtract(x, y));
    }
}
 
// This code is contributed by 
// Smitha Dinesh Semwal.
 
 

Python3




# Python  Program to
# subtract two Number
# without using arithmetic operator
# Recursive implementation.
 
def subtract(x, y):
 
    if (y == 0):
        return x
    return subtract(x ^ y, (~x & y) << 1)
 
# Driver program
x = 29
y = 13
print("x - y is", subtract(x, y))
 
# This code is contributed by
# Smitha Dinesh Semwal
 
 

C#




// C# Program to subtract two Number
// without using arithmetic operator
// Recursive implementation.
using System;
 
class GFG {
 
    static int subtract(int x, int y)
    {
        if (y == 0)
            return x;
 
        return subtract(x ^ y, (~x & y) << 1);
    }
 
    // Driver program
    public static void Main()
    {
        int x = 29, y = 13;
        Console.WriteLine("x - y is "+
                            subtract(x, y));
    }
}
 
// This code is contributed by anuj_67.
 
 

PHP




<?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);
 
# This code is contributed by ajit
?>
 
 

Javascript




<script>
// javascript  Program to subtract two Number
// without using arithmetic operator
// Recursive implementation.  
function subtract(x , y)
{
 
    if (y == 0)
        return x;
 
    return subtract(x ^ y, (~x & y) << 1);
}
 
// Driver program
var x = 29, y = 13;
document.write("x - y is "+
                    subtract(x, y));
 
// This code is contributed by Princi Singh
</script>
 
 

Output : 

x - y is 16

Time Complexity: O(log y)

Auxiliary Space: O(log y)

This article is contributed Dheeraj.
 



Next Article
To find sum of two numbers without using any operator
author
kartik
Improve
Article Tags :
  • Bit Magic
  • DSA
Practice Tags :
  • Bit Magic

Similar Reads

  • Add two numbers without using arithmetic operators
    Given two integers a and b, the task is to find the sum of a and b without using + or - operators. Examples: Input: a = 10, b = 30Output: 40 Input: a = -1, b = 2Output: 1 Approach: The approach is to add two numbers using bitwise operations. Let's first go through some observations: a & b will h
    5 min read
  • Subtract 1 without arithmetic operators
    Write a program to subtract one from a given number. The use of operators like ‘+’, ‘-‘, ‘*’, ‘/’, ‘++’, ‘–‘ …etc are not allowed. Examples: Input: 12Output: 11 Input: 6Output: 5 Bitwise Subtraction ApproachTo subtract 1 from a number x (say 0011001000), flip all the bits after the rightmost 1 bit (
    5 min read
  • To find sum of two numbers without using any operator
    Write a program to find sum of positive integers without using any operator. Only use of printf() is allowed. No other library function can be used. Solution It's a trick question. We can use printf() to find sum of two numbers as printf() returns the number of characters printed. The width field in
    9 min read
  • C++ program to divide a number by 3 without using *, / , +, -, % operators
    For a given positive number we need to divide a number by 3 without using any of these *, /, +, – % operatorsExamples: Input : 48 Output : 16 Input : 16 Output : 5 Algorithm Take a number num, sum = 0while(num>3), shift the number left by 2 bits and sum = add(num >> 2, sum). Create a functi
    2 min read
  • Minimizing numbers through subtraction operations
    Given two numbers given as P and Q, the task is to make both numbers equal in the minimum number of operations, where you are allowed to perform the below operations any number of times: If P > Q, replace P with P − Q;If Q < P, replace Q with Q − P.Examples: Input: P = 100001, Q = 100001Output
    5 min read
  • Javascript program to swap two numbers without using temporary variable
    To swap two numbers without using a temporary variable, we have multiple approaches. In this article, we are going to learn how to swap two numbers without using a temporary variable. Below are the approaches used to swap two numbers without using a temporary variable: Table of Content Using Arithme
    6 min read
  • Multiplication of two numbers with shift operator
    For any given two numbers n and m, you have to find n*m without using any multiplication operator. Examples : Input: n = 25 , m = 13 Output: 325 Input: n = 50 , m = 16 Output: 800 Method 1We can solve this problem with the shift operator. The idea is based on the fact that every number can be repres
    7 min read
  • Repeated subtraction among two numbers
    Given a pair of positive numbers x and y. We repeatedly subtract the smaller of the two integers from greater one until one of the integers becomes 0. The task is to count number of steps to before we stop (one of the numbers become 0). Examples : Input : x = 5, y = 13 Output : 6 Explanation : There
    6 min read
  • Addition of two numbers without propagating Carry
    Given 2 numbers a and b of same length. The task is to calculate their sum in such a way that when adding two corresponding positions the carry has to be kept with them only instead of propagating to the left.See the below image for reference: Examples: Input: a = 7752 , b = 8834 Output: 151586 Inpu
    15 min read
  • Find Quotient and Remainder of two integer without using division operators
    Given two positive integers dividend and divisor, our task is to find quotient and remainder. The use of division or mod operator is not allowed. Examples: Input : dividend = 10, divisor = 3 Output : 3, 1 Explanation: The quotient when 10 is divided by 3 is 3 and the remainder is 1. Input : dividend
    10 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences