Finding nearest Gapful number in JavaScript


A number is a gapful number when −

  • It has at least three digits, and
  • It is exactly divisible by the number formed by putting its first and last digits together

For example −

The number 1053 is a gapful number because it has 4 digits and it is exactly divisible by 13. Similarly, 135 is a gapful number because it has 3 digits and it is exactly divisible by 15.

Our job is to write a program that returns the nearest gapful number to the number we provide as input.

For example, for all 2-digit numbers, it would be 100. For 103, it would be 105.

We will break the problem into two functions −

isGapful() function

It receives a number string and returns a boolean as in the below code −

const isGapful = (numStr) => {
   const int = parseInt(numStr);
   return int % parseInt(numStr[0] + numStr[numStr.length - 1]) === 0;
};

nearestGapful() function

This is our main function that receives a number, returns the nearest gapful number. Here’s the code −

const nearestGapful = (num) => {
   if(typeof num !== 'number'){
      return -1;
   }
   if(num <= 100){
      return 100;
   }
   let prev = num - 1, next = num + 1;
   while(!isGapful(String(prev)) && !isGapful(String(next))){
      prev--;
      next++;
   };
   return isGapful(String(prev)) ? prev : next;
};

The isGapful() function returns a boolean based on whether the number is gapful or not in constant time, the nearestGapful() function loops until it finds a number that is gapful and returns it.

Following is the complete code −

Example

const n = 134;
//receives a number string and returns a boolean
const isGapful = (numStr) => {
   const int = parseInt(numStr);
   return int % parseInt(numStr[0] + numStr[numStr.length - 1]) === 0;
};
//main function -- receives a number, returns a number
const nearestGapful = (num) => {
   if(typeof num !== 'number'){
      return -1;
   }
   if(num <= 100){
      return 100;
   }
   let prev = num - 1, next = num + 1;
   while(!isGapful(String(prev)) && !isGapful(String(next))){
      prev--;
      next++;
   };
   return isGapful(String(prev)) ? prev : next;
};
console.log(nearestGapful(n));

Output

The output in the console will be −

135

Updated on: 19-Aug-2020

80 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements