- Related Questions & Answers
- Program to find sum of series 1 + 1/2 + 1/3 + 1/4 + .. + 1/n in C++
- Find product of prime numbers between 1 to n in C++
- C++ program to find the sum of the series 1 + 1/2^2 + 1/3^3 + …..+ 1/n^n
- Program to find sum of 1 + x/2! + x^2/3! +…+x^n/(n+1)! in C++
- Sum of the series Kn + ( K(n-1) * (K-1)1 ) + ( K(n-2) * (K-1)2 ) + ... (K-1)n in C++
- Find count of Almost Prime numbers from 1 to N in C++
- Find consecutive 1s of length >= n in binary representation of a number in C++
- C/C++ Program to Find sum of Series with n-th term as n power of 2 - (n-1) power of 2
- Program to find sum of series 1*2*3 + 2*3*4+ 3*4*5 + . . . + n*(n+1)*(n+2) in C++
- Program to find sum of prime numbers between 1 to n in C++
- Find median of BST in O(n) time and O(1) space in C++
- Find the value of ln(N!) using Recursion using C++.
- Count number of binary strings of length N having only 0’s and 1’s in C++
- Sum of the series 1^1 + 2^2 + 3^3 + ... + n^n using recursion in C++
- Sum of the series 1.2.3 + 2.3.+ … + n(n+1)(n+2) in C

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who

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.**142857**142857… 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.

#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; }

Period length of 1/7 is: 6

Advertisements