Finding minimum number of required operations to reach n from m in JavaScript


Problem

We are required to write a JavaScript function that takes in two numbers, m and n, as the first and the second argument.

Our function is supposed to count the number of minimum operations required to reach n from m, using only these two operations −

  • Double − Multiply the number on the display by 2, or;

  • Decrement − Subtract 1 from the number on the display.

For example, if the input to the function is −

const m = 5;
const n = 8;

Then the output should be −

const output = 8;

Output Explanation:

Because the operations are −

5 → 4 → 8

Example

The code for this will be −

 Live Demo

const m = 5;
const n = 8;
const findOperations = (m, n) => {
   let res = 0;
   while(n > m){
      if(n % 2 === 0){
         n /= 2;
      }else{
         n += 1;
      };
      res += 1;
   };
   return res + m - n;
};
console.log(findOperations(m, n));

Output

And the output in the console will be −

2

Updated on: 09-Apr-2021

83 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements