Finding the sum of two numbers without using '+', '-', '/', '*' in JavaScript

JavascriptWeb DevelopmentFront End Technology

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.

Example

The code for this will be −

 Live Demo

const m = 67, n = 33;
const add = (x, y) => {
   while(y !== 0){
      let carry = x & y;
      x = x ^ y;
      y = carry << 1;
   };
   return x;
};
console.log(add(m, n));

Explanation

Sum of two bits can be obtained by performing XOR (^) of the two bits. And the carry bit can be obtained by performing AND (&) of two bits.

We have here used an extended version of the Half Adder logic that can be used to add 2 single bits to add two integers. If x and y don’t have set bits at the 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 have calculated (x & y) << 1 and added it to x ^ y to get the required result.

Output

And the output in the console will be −

100
raja
Published on 03-Mar-2021 05:51:42
Advertisements