- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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 −
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
Advertisements