Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Finding the sum of two numbers without using '+', '-', '/', '*' in JavaScript
We are required to write a JavaScript function add() that takes in two numbers m and n. The function should, without using the four basic arithmetic operations add the two numbers taken as input and return the sum.
The Challenge
Without using +, -, *, or /, we need to implement addition using bitwise operations. This approach mimics how computers perform addition at the hardware level using binary logic.
Example
The code for this will be ?
const m = 67, n = 33;
const add = (x, y) => {
while(y !== 0){
let carry = x & y;
x = x ^ y;
y = carry
Output
And the output in the console will be ?
100
How It Works
This solution uses the Half Adder logic from digital electronics. Here's the step-by-step process:
1. XOR Operation (^): Sum of two bits can be obtained by performing XOR of the two bits. This gives us the sum without considering the carry.
2. AND Operation (&): The carry bit can be obtained by performing AND of two bits. This identifies positions where both bits are 1.
3. Left Shift ( We shift the carry left by 1 position because carry affects the next higher bit position.
Step-by-Step Example
Let's trace through adding 67 + 33:
// Initial: x = 67 (1000011), y = 33 (0100001)
console.log("Step 1: x =", 67, "y =", 33);
// Iteration 1:
let carry = 67 & 33; // carry = 1 (0000001)
let x1 = 67 ^ 33; // x = 98 (1100010)
let y1 = carry
Step 1: x = 67 y = 33
After iteration 1: x = 98 y = 2
After iteration 2: x = 96 y = 4
Final result: 100
Key Points
- XOR (^) performs addition without carry
- AND (&) identifies carry positions
- Left shift (
- Loop continues until no carry remains (y becomes 0)
Conclusion
This bitwise approach demonstrates how computers perform addition at the hardware level. By using XOR for sum and AND with left shift for carry, we can add numbers without traditional arithmetic operators.
