
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- 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 Smallest Number That Satisfies Conditions in JavaScript
We are required to write a JavaScript function that takes in a number as the first argument, say n, and an array of numbers as the second argument. The function should return the smallest n digit number which is a multiple of all the elements specified in the array.
If there exist no such n digit element then we should return the smallest such element.
For example: If the array is −
const arr = [12, 4, 5, 10, 9]
For both n = 2 and n = 3,
Output
The output should be −
180
Therefore, let’s write the code for this function −
Example
The code for this will be −
const arr = [12, 4, 5, 10, 9] const num1 = 2; const num2 = 3; const allDivides = (arr, num) => arr.every(el => num % el === 0); const smallestMultiple = (arr, num) => { let smallestN = Math.pow(10, (num - 1)); while(!allDivides(arr, smallestN)){ smallestN++; }; return smallestN; }; console.log(smallestMultiple(arr, num1)); console.log(smallestMultiple(arr, num2));
Output
The output in the console will be −
180 180
Advertisements