Finding length of repeating decimal part in JavaScript

When dividing 1 by certain numbers, the decimal result may have a repeating pattern. This function finds the length of that repeating decimal part, but only for numbers that are coprime with 10 (share no common factors except 1).

Problem Statement

We need to write a JavaScript function that:

  • Checks if a number is coprime with 10 (shares no common factors except 1)
  • If not coprime, returns -1
  • If coprime, returns the length of the repeating decimal part when 1 is divided by that number

Understanding Coprime with 10

A number is coprime with 10 if it's not divisible by 2 or 5 (since 10 = 2 × 5). Numbers divisible by 2 or 5 produce terminating decimals, not repeating ones.

Example Walkthrough

For num = 123:

// 1 ÷ 123 = 0.008130081300813...
console.log(1 / 123);
0.008130081300813008130081300813

The decimal part "00813" repeats infinitely with length 5.

Algorithm

The algorithm uses modular arithmetic to simulate long division:

  1. Check if number is divisible by 2 or 5 (not coprime with 10)
  2. Start with remainder 10 % num
  3. Keep multiplying remainder by 10 and taking modulo until we get remainder 1
  4. Count the steps - this gives the repeating cycle length

Implementation

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));
5

Testing with Different Numbers

// Test cases
console.log("7:", findRepeatingPart(7));   // 1/7 = 0.142857...
console.log("11:", findRepeatingPart(11)); // 1/11 = 0.090909...
console.log("13:", findRepeatingPart(13)); // 1/13 = 0.076923...
console.log("6:", findRepeatingPart(6));   // Not coprime with 10
console.log("25:", findRepeatingPart(25)); // Not coprime with 10

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;
   }
};
7: 6
11: 2
13: 6
6: -1
25: -1

Key Points

  • Only works for numbers coprime with 10 (not divisible by 2 or 5)
  • Uses modular arithmetic to simulate long division efficiently
  • The cycle length equals the multiplicative order of 10 modulo the given number
  • Returns -1 for numbers that produce terminating decimals

Conclusion

This algorithm efficiently finds the repeating decimal length using modular arithmetic instead of actual division. It's based on number theory principles and works only for numbers coprime with 10.

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

473 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements