Sunday, November 17, 2024
Google search engine
HomeData Modelling & AIFind length of period in decimal value of 1/n

Find length of period in decimal value of 1/n

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. 
Examples : 
 

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.
 

CPP




// C++ program to find length of period of 1/n
#include <iostream>
#include <map>
using namespace std;
  
// Function to find length of period in 1/n
int getPeriod(int n)
{
   // Create a map to store mapping from remainder
   // its position
   map<int, int> mymap;
   map<int, int>::iterator it;
  
   // Initialize remainder and position of remainder
   int rem = 1, i = 1;
  
   // Keep finding remainders till a repeating remainder
   // is found
   while (true)
   {
        // Find next remainder
        rem = (10*rem) % n;
  
        // If remainder exists in mymap, then the difference
        // between current and previous position is length of
        // period
        it = mymap.find(rem);
        if (it != mymap.end())
            return (i - it->second);
  
        // If doesn't exist, then add 'i' to mymap
        mymap[rem] = i;
        i++;
   }
  
   // This code should never be reached
   return INT_MAX;
}
  
// Driver program to test above function
int main()
{
    cout <<  getPeriod(3) << endl;
    cout <<  getPeriod(7) << endl;
    return 0;
}


Java




// Java program to find length of period of 1/n
import java.util.*;
  
class GFG {
  
  // Function to find length of period in 1/n
  static int getPeriod(int n)
  {
  
    // Create a map to store mapping from remainder
    // its position
    HashMap<Integer, Integer> mymap
      = new HashMap<Integer, Integer>();
  
    // Initialize remainder and position of remainder
    int rem = 1, i = 1;
  
    // Keep finding remainders till a repeating
    // remainder is found
    while (true) {
      // Find next remainder
      rem = (10 * rem) % n;
  
      // If remainder exists in mymap, then the
      // difference between current and previous
      // position is length of period
      if (mymap.containsKey(rem)) {
        int it = mymap.get(rem);
        return i - it;
      }
  
      // If doesn't exist, then add 'i' to mymap
      mymap.put(rem, i);
      i++;
    }
  }
  
  // Driver program to test above function
  public static void main(String[] args)
  {
    System.out.println(getPeriod(3));
    System.out.println(getPeriod(7));
  }
}
  
// This code is contributed by phasing17


Python3




# Python3 program to find length of period of 1/n
import sys
  
# Function to find length of period in 1/n
def getPeriod(n):
     
   # Create a map to store mapping from remainder
   # its position
   mymap = dict()
  
   # Initialize remainder and position of remainder
   rem = 1
   i = 1
   pos = 0
  
   # Keep finding remainders till a repeating remainder
   # is found
   while True:
     
        # Find next remainder
        rem = (10 * rem) % n
  
        # If remainder exists in mymap, then the difference
        # between current and previous position is length of
        # period
        if (rem in mymap):
            return (i - mymap[rem])
  
        # If doesn't exist, then add 'i' to mymap
        mymap[rem] = i
        i += 1
     
   # This code should never be reached
   return sys.maxint
  
# Driver program to test above function
print(getPeriod(3))
print(getPeriod(7))
  
# This code is contributed by phasing17


C#




// C# program to find length of period of 1/n
using System;
using System.Collections.Generic;
  
class GFG
{
  
  // Function to find length of period in 1/n
  static int getPeriod(int n)
  {
  
    // Create a map to store mapping from remainder
    // its position
    Dictionary<int, int> mymap
      = new Dictionary<int, int>();
  
    // Initialize remainder and position of remainder
    int rem = 1, i = 1;
  
    // Keep finding remainders till a repeating
    // remainder is found
    while (true) {
      // Find next remainder
      rem = (10 * rem) % n;
  
      // If remainder exists in mymap, then the
      // difference between current and previous
      // position is length of period
      if (mymap.ContainsKey(rem)) {
        var it = mymap[rem];
        return i - it;
      }
  
      // If doesn't exist, then add 'i' to mymap
      mymap[rem] = i;
      i++;
    }
  
  
  }
  
  // Driver program to test above function
  public static void Main(string[] args)
  {
    Console.WriteLine(getPeriod(3));
    Console.WriteLine(getPeriod(7));
  }
}
  
// This code is contributed by phasing17


Javascript




// JavaScript program to find length of period of 1/n
  
  
// Function to find length of period in 1/n
function getPeriod(n)
{
   // Create a map to store mapping from remainder
   // its position
   let mymap = {};
  
   // Initialize remainder and position of remainder
   let rem = 1, i = 1;
   let pos = 0;
  
   // Keep finding remainders till a repeating remainder
   // is found
   while (true)
   {
        // Find next remainder
        rem = (10 * rem) % n;
  
        // If remainder exists in mymap, then the difference
        // between current and previous position is length of
        // period
        if (mymap.hasOwnProperty(rem))
            return (i - mymap[rem]);
  
        // If doesn't exist, then add 'i' to mymap
        mymap[rem] = i;
        i++;
   }
  
   // This code should never be reached
   return Number.MAX_SAFE_INTEGER;
}
  
// Driver program to test above function
console.log(getPeriod(3));
console.log(getPeriod(7));
  
  
// This code is contributed by phasing17


Output:

1
6

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. 
 

C++




// C++ program to find length of period of 1/n without 
// using map or hash
#include <iostream>
using namespace std;
  
// Function to find length of period in 1/n
int getPeriod(int n)
{
   // Find the (n+1)th remainder after decimal point
   // in value of 1/n
   int rem = 1; // Initialize remainder
   for (int i = 1; i <= n+1; i++)
         rem = (10*rem) % n;
  
   // Store (n+1)th remainder
   int d = rem;
  
   // Count the number of remainders before next
   // occurrence of (n+1)'th remainder 'd'
   int count = 0;
   do {
      rem = (10*rem) % n;
      count++;
   } while(rem != d);
  
   return count;
}
  
// Driver program to test above function
int main()
{
    cout <<  getPeriod(3) << endl;
    cout <<  getPeriod(7) << endl;
    return 0;
}


Java




// Java program to find length 
// of period of 1/n without using 
// map or hash
  
class GFG {
      
// Function to find length of period in 1/n
static int getPeriod(int n)
{
    // Find the (n+1)th remainder after
    // decimal point in value of 1/n
      
    int rem = 1; // Initialize remainder
    for (int i = 1; i <= n + 1; i++)
            rem = (10 * rem) % n;
      
    // Store (n+1)th remainder
    int d = rem;
      
    // Count the number of remainders before next
    // occurrence of (n+1)'th remainder 'd'
    int count = 0;
    do {
        rem = (10 * rem) % n;
        count++;
    } while(rem != d);
      
    return count;
}
  
// Driver code
public static void main(String[] args)
{
    System.out.println(getPeriod(3) );
    System.out.println(getPeriod(7));
}
}
  
// This code is contributed by Smitha Dinesh Semwal


Python3




# Python3 program to find length of
# period of 1/n without using map or hash 
  
# Function to find length
# of period in 1/n 
def getPeriod( n) :
  
    # Find the (n+1)th remainder after 
    # decimal point in value of 1/n 
    rem = 1 # Initialize remainder 
    for i in range(1, n + 2): 
        rem = (10 * rem) % n
  
    # Store (n+1)th remainder 
    d = rem
      
    # Count the number of remainders 
    # before next occurrence of 
    # (n+1)'th remainder 'd' 
    count = 0
    rem = (10 * rem) % n
    count += 1
    while rem != d :
        rem = (10 * rem) % n
        count += 1
      
    return count
  
# Driver Code
if __name__ == "__main__":
  
    print (getPeriod(3))
    print (getPeriod(7))
  
# This code is contributed 
# by ChitraNayal


C#




// C# program to find length of
// period of 1/n without using 
// map or hash
using System;
  
class GFG {
      
// Function to find length of period in 1/n
static int getPeriod(int n)
{
    // Find the (n+1)th remainder after 
    // decimal point in value of 1/n
      
    int rem = 1; // Initialize remainder
    for (int i = 1; i <= n + 1; i++)
            rem = (10 * rem) % n;
      
    // Store (n+1)th remainder
    int d = rem;
      
    // Count the number of remainders before next
    // occurrence of (n+1)'th remainder 'd'
    int count = 0;
    do {
        rem = (10 * rem) % n;
        count++;
    } while(rem != d);
      
    return count;
}
  
// Driver code
public static void Main()
{
    Console.Write(getPeriod(3) + "\n");
    Console.Write(getPeriod(7));
}
}
  
// This code is contributed by Smitha Dinesh Semwal


PHP




<?php
// PHP program to find length
// of period of 1/n without 
// using map or hash
  
// Function to find length
// of period in 1/n
function getPeriod($n)
{
    // Find the (n+1)th remainder
    // after decimal point
    // in value of 1/n
      
    // Initialize remainder
    $rem = 1; 
    for ($i = 1; $i <= $n + 1; $i++)
        $rem = (10 * $rem) % $n;
  
    // Store (n+1)th 
    // remainder
    $d = $rem;
  
    // Count the number of 
    // remainders before next
    // occurrence of (n+1)'th
    // remainder 'd'
    $count = 0;
    do 
    {
        $rem = (10 * $rem) % $n;
        $count++;
    } while($rem != $d);
      
    return $count;
}
  
    // Driver Code
    echo getPeriod(3), "\n";
    echo getPeriod(7), "\n";
      
// This code is contributed by ajit.
?>


Javascript




<script>
  
// Javascript program to find length 
// of period of 1/n without using 
// map or hash
  
    // Function to find length of period in 1/n
    function getPeriod(n)
    {
        // Find the (n+1)th remainder after
        // decimal point in value of 1/n
          
        let rem = 1; // Initialize remainder
        for (let i = 1; i <= n + 1; i++)
            rem = (10 * rem) % n;
          
        // Store (n+1)th remainder
        let d = rem;
          
        // Count the number of remainders before next
        // occurrence of (n+1)'th remainder 'd'
        let count = 0;
        do {
            rem = (10 * rem) % n;
            count++;
        } while(rem != d);
            
        return count;
    }
      
    // Driver code
    document.write(getPeriod(3)+"<br>")
    document.write(getPeriod(7)+"<br>")
      
    // This code is contributed by rag2127
      
</script>


Output:

1
6

Reference: 
Algorithms And Programming: Problems And Solutions by Alexander Shen
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.
 

Feeling lost in the world of random DSA topics, wasting time without progress? It’s time for a change! Join our DSA course, where we’ll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 neveropen!

RELATED ARTICLES

Most Popular

Recent Comments