Finding length of repeating decimal part in JavaScript

JavascriptWeb DevelopmentFront End Technology

Problem

We are required to write a JavaScript function that takes in a number, num, as the first and the only argument

Our function should do two things

  • First of all, it should check whether the number is prime with 10 or not, if its not, we should return -1 (a number is prime with any other number if the only common factor they share is 1).
  • If the number is prime with 10, then we should return the length of the decimal part which repeats itself, when that very number divides 1.

For example, if the input to the function is −

Input

const num = 123;

Output

const output = 5;

Output Explanation

Because the number 123 is prime with 10 for sure

And when we divide 1 by 123, we get −

1 / 123 = 0.008130081300813…

This clearly shows that the decimal part 00813 is getting repeated infinitely and its length is 5, hence our output is 5.

Example

Following is the code −

 Live Demo

const num = 123;
const findRepeatingPart = (num = 1) => {
   if(num % 2 === 0 || num % 5 === 0){
      return -1;
   } else {
      let res = 10 % num, count = 1;
      while(res != 1){

         res = res * 10 % num;
         count++;
      };
      return count;
   }
};
console.log(findRepeatingPart(num));

Output

5
raja
Published on 22-Apr-2021 11:09:34
Advertisements