- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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
#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
- Related Articles
- Find value of (n^1 + n^2 + n^3 + n^4) mod 5 for given n in C++
- Find the value of : $frac{1}{1+a^{n-m}}+frac{1}{1+a^{m-n}}$.
- Find the value of n:$8n + 8n + 1 = 72$
- If $1+2+3+........+n=78$, then find the value of $n$.
- Find consecutive 1s of length >= n in binary representation of a number in C++
- Find N % (Remainder with 4) for a large value of N in C++
- Calculate the value of (m)1/n in JavaScript
- Maximum value of |arr[0] – arr[1] - + |arr[1] – arr[2] - + … +|arr[n – 2] – arr[n – 1] - when elements are from 1 to n in C++
- If $frac{n}{4}-5=frac{n}{6}+frac{1}{2}$, find the value of $n$.
- Find sum of Series with n-th term as n^2 - (n-1)^2 in C++
- Program to find sum of 1 + x/2! + x^2/3! +…+x^n/(n+1)! in C++
- Find product of prime numbers between 1 to n in C++
- Program to find sum of series 1 + 1/2 + 1/3 + 1/4 + .. + 1/n in C++
- Count number of binary strings of length N having only 0’s and 1’s in C++
- If the numbers $n−2, 4n−1$ and $5n+2$ are in A.P., find the value of $n$.

Advertisements