Find length of period in decimal value of 1/n in C++


Suppose we have a number n. We have to find the length of period in decimal value of 1/n. So if the value of n is 7, then 1/7 = 0.142857142857… That part in bold letters are repeating. So here the length of period is 6.

For a number n, there can be n distinct remainders in the output, but the period may not begin from the first remainder as some initial remainders are non-repeating. So we have to make sure that a remainder from period is picked, start from (n+1)th remainder, and start looking for the next occurrence. The distance between (n+1)th remainder and the next occurrence, is the length of the period.

Example

 Live Demo

#include<iostream>
using namespace std;
int periodLength(int n) {
   int remainder = 1;
   int length = 0;
   for (int i = 1; i <= n+1; i++)
   remainder = (10*remainder) % n;
   int d = remainder;
   do {
      remainder = (10*remainder) % n;
      length++;
   } while(remainder != d);
      return length;
}
int main() {
   int n = 7;
   cout << "Period length of 1/"<<n<<" is: " << periodLength(n) << endl;
}

Output

Period length of 1/7 is: 6

Updated on: 18-Dec-2019

518 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements