Given a positive integer n, find the period in decimal value of 1/n. Period in decimal value is number of digits (somewhere after decimal point) that keep repeating.
Input: n = 3 Output: 1 The value of 1/3 is 0.333333... Input: n = 7 Output: 6 The value of 1/7 is 0.142857142857142857..... Input: n = 210 Output: 6 The value of 1/210 is 0.0047619047619048.....
Let us first discuss a simpler problem of finding individual digits in value of 1/n.
How to find individual digits in value of 1/n?
Let us take an example to understand the process. For example for n = 7. The first digit can be obtained by doing 10/7. Second digit can be obtained by 30/7 (3 is remainder in previous division). Third digit can be obtained by 20/7 (2 is remainder of previous division). So the idea is to get the first digit, then keep taking value of (remainder * 10)/n as next digit and keep updating remainder as (remainder * 10) % 10. The complete program is discussed here.
How to find the period?
The period of 1/n is equal to the period in sequence of remainders used in the above process. This can be easily proved from the fact that digits are directly derived from remainders.
One interesting fact about sequence of remainders is, all terns in period of this remainder sequence are distinct. The reason for this is simple, if a remainder repeats, then it’s beginning of new period.
Following is the implementation of above idea.
We can avoid the use of map or hash using the following fact. For a number n, there can be at most n distinct remainders. Also, the period may not begin from the first remainder as some initial remainders may be non-repetitive (not part of any period). So to make sure that a remainder from a period is picked, start from the (n+1)th remainder and keep looking for its next occurrence. The distance between (n+1)’th remainder and its next occurrence is the length of the period.
This article is contributed by Sachin. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
- Program to find whether a no is power of two
- Program to find parity
- Find minimum number to be divided to make a number a perfect square
- Find whether a given number is a power of 4 or not
- Find Union and Intersection of two unsorted arrays
- Print all sequences of given length
- To find sum of two numbers without using any operator
- Find day of the week for a given date
- Given a number, find the next smallest palindrome
- Find the element that appears once
- Find the largest multiple of 2, 3 and 5
- Program to find amount of water in a given glass
- Find the maximum distance covered using n bikes
- Find if two rectangles overlap
- Find the smallest number whose digits multiply to a given number n