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

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

+6
math algorithm
source share
3 answers

Just do a long high school split:

 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 should detect when 1 / n has a final representation less than k .

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

Note that by changing value *= 10 to value *= b , you can also print a b-ary representation of 1 / n .

+6
source share

Computing 10 ^ K / N can be extremely expensive for large K and small N.

This is probably closer to a good solution: a long split . This is how we divided the numbers before the calculators. :)

Obviously, you should only run this algorithm until it gives K digits.

+4
source share

If these are the first k digits, is it not very straightforward to multiply the numerator by 10 ^ k, and therefore it becomes easier to divide by N? And if we need an answer, that is, a decimal representation, then we will finish dividing the result by 10 ^ K again, so that the previous multiplication resets to zero.

+1
source share

All Articles