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.

Updated on: 2026-03-15T23:19:00+05:30

412 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements