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
Selected Reading
Greatest number divisible by n within a bound in JavaScript
Problem
We need to write a JavaScript function that takes in a divisor number n and a bound number b.
Our function should find the largest integer num, such that:
num is divisible by n (the divisor)
num is less than or equal to b (the bound)
num is greater than 0
Brute Force Approach
The straightforward approach is to iterate through all multiples of n and find the largest one within the bound:
const n = 14;
const b = 400;
const biggestDivisible = (n, b) => {
let max = 0;
for(let j = n; j max){
max = j;
}
}
return max;
};
console.log(biggestDivisible(n, b));
392
Optimized Mathematical Approach
Instead of iterating, we can calculate the result directly using mathematical division:
const biggestDivisibleOptimized = (n, b) => {
if (n
392
49
9
Comparison
| Approach | Time Complexity | Efficiency |
|---|---|---|
| Brute Force Loop | O(b/n) | Slower for large bounds |
| Mathematical | O(1) | Instant calculation |
Edge Cases
Handle edge cases where inputs might be invalid:
const safeBiggestDivisible = (n, b) => {
if (n b) return 0;
return Math.floor(b / n) * n;
};
console.log(safeBiggestDivisible(14, 400)); // 392
console.log(safeBiggestDivisible(50, 10)); // 0 (divisor > bound)
console.log(safeBiggestDivisible(-5, 20)); // 0 (negative divisor)
392 0 0
Conclusion
The mathematical approach using Math.floor(b / n) * n is the most efficient solution with O(1) time complexity. Always validate inputs to handle edge cases properly.
Advertisements
