Numbers obtained during checking divisibility by 7 using JavaScript



Problem

We can check for a number to be divisible by 7 if it is of the form 10a + b and a - 2b is divisible by 7.

We continue to do this until a number known to be divisible by 7 is obtained; we can stop when this number has at most 2 digits because we are supposed to know if a number of at most 2 digits is divisible by 7 or not.

We are required to write a JavaScript function that takes in a number and return the number of such steps required to reduce the number to a two-digit number at most and that two digit number.

Input

const num = 1603;

Output

const output = [7, 2];

Because the steps are −

160 - 2*3 = 154
15 - 2*8 = 7

And the final value is 7

Example

Following is the code −

 Live Demo

const num = 1603;
const findSteps = (num) => {
   let times = 0;
   let result = 0;
   let number = String(num);
   while(number.length > 2){
      times++;
      let firstNumber = Number(number.slice(-1))
      const remaining = Number(number.slice(0, number.length - 1))
      result = remaining - 2 * firstNumber
      number = String(result)
   }
   return [result, times]
}
console.log(findSteps(num));

Output

[7, 2]

Advertisements