We have a floating point number r
between 0 and 1, and an integer p
.
Find the fraction of integers with the smallest denominator, which approximates r
with at least p
-digit precision.
- Inputs:
r
(a floating point number) andp
(integer). - Outputs:
a
andb
integers, wherea/b
(as float) approximatesr
untilp
digits.b
is the possible smallest such positive integer.
For example:
- if
r=0.14159265358979
andp=9
, - then the result is
a=4687
andb=33102
, - because
4687/33102=0.1415926530119026
.
Any solution has to work in theory with arbitrary-precision types, but limitations caused by implementations' fixed-precision types do not matter.
Precision means the number of digits after "0.
" in r
. Thus, if r=0.0123
and p=3
, then a/b
should start with 0.012
. If the first p
digits of the fractional part of r
are 0, undefined behavior is acceptable.
Win criteria:
- The algorithmically fastest algorithm wins. Speed is measured in O(p).
- If there are multiple fastest algorithms, then the shortest wins.
- My own answer is excluded from the set of the possible winners.
P.s. the math part is actually much easier as it seems, I suggest to read this post.