Finding Gapful number in JavaScript


A number is gapful if it is at least 3 digits long and is divisible by the number formed by stringing the first and last numbers together. The smallest number that fits this description is 100. First digit is 1, last digit is 0, forming 10, which is a factor of 100. Therefore, 100 is gapful.

We are required to create a function that takes a number n and returns the closest gapful number (including itself). If there are 2 gapful numbers that are equidistant to n, return the lower one.

Some examples −

gapful(25) ➞ 100

gapful(100) ➞ 100

gapful(103) ➞ 105

Example

Following is the code −

const num = 4780;
const isGapful = n => {
   if (n < 100){
      return false;
   }
   const temp = Array.from(n.toString());
   return n % (temp[0] + temp[temp.length - 1]) === 0;
}
function getClosestGapful(n) {
   let left = n, right = n;
   while (!isGapful(right)){
      right++;
   }
   if (n < 100){
      return right;
   }
   while (!isGapful(left)){
      left++;
   }
   return n - left <= right - n ? left : right;
};
console.log(getClosestGapful(25));
console.log(getClosestGapful(num));

Output

This will produce the following output on console −

100
4800

Updated on: 01-Oct-2020

239 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements