

How to find K first digits of the decimal representation of 1 / N
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
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.
Recommend
-
100
NVIDIA DIGITS(非常好用的一个框架) Original...
-
125
Using digits to select company-mode candidates 27 Dec 2017 I'd like to share a customization of company-mode that I've been using for a while. I refined it ju...
-
74
A Million Digits of Pi in 9 Lines of Javascript
-
30
circle visualization of a number's digits in Go Introduction In the image below, each dot represents a deci...
-
9
Working with ImageNet (ILSVRC2012) Dataset in NVIDIA DIGITS Dec 1, 2017 Recently I had the chance/need to re-train some Caffe CNN models with the ImageNet image classification dataset. I wanted to use NVIDIA DIGITS as th...
-
3
Python 2.7, Spyder, Keep significant digits before a decimal advertisements I am trying to figure out how to keep all significant figures in a...
-
5
How To Generate A Valid Credit Card Number For A Bin (First 6 Digits) March 25, 2014 There is plenty of generators that can p...
-
8
C++ Program to Find the Sum of All Digits of a NumberC++ Program to Find the Sum of All Digits of a Number20 Views30/05/2022In this video,...
-
12
Find First and Last Digits of a Number in PHP ...
-
8
Amazon cost cuts lift operating margin to double digits for first timeKey PointsIn this article
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK