5

How to find K first digits of the decimal representation of 1 / N

 2 years ago
source link: https://www.codesd.com/item/how-to-find-k-first-digits-of-the-decimal-representation-of-1-n.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

How to find K first digits of the decimal representation of 1 / N

advertisements

This is an interview question I came across: find K first digits of the decimal representation of 1/N. It looks like we need just calculate 10^K/N to solve the problem. Does it make sense ? It looks like I am missing something because the solution is too easy.


Just implement grade-school long division:

int value = 1;
bool outputDecimalSeparator = false;
int digitsOutput = 1;
while(digitsOutput <= k) {
    if (value == 0) {
        Console.Write(0);
    }
    else {
        if (value < n) {
            Console.Write(0);
            value *= 10;
        }
        else {
            Console.Write(value / n);
            value %= n;
        }
   }
   if (outputDecimalSeparator == false) {
       outputDecimalSeparator = true;
       Console.Write('.');
   }
   digitsOutput++;
}
Console.WriteLine();

The branch on value == 0 is to detect when 1 / n has a terminating representation of less than k digits.

Here, n is the denominator in 1 / n and k is the number of digits to print in the decimal representation of 1 / n.

Note that by changing value *= 10 to value *= b you can print the b-ary representation of 1 / n as well.


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK