BestApproximationDiv2
SRM 483 · 2010-03-12 · by espr1t
Problem Statement
Elly understands that working with infinite decimal fractions is going to be very difficult, so she first wants to find a good way to approximate floating point numbers with decimal representations that are finite. Your task is to help her in this mission. You will be given a
Given a fraction F = A/B, where 0 <= A < B, its quality of approximation with respect to number is calculated as follows:
- Let S be the decimal fraction (infinite or finite) representation of F.
- Let N be the number of digits after the decimal point in number. If number has trailing zeros, all of them are considered to be significant and are counted towards N.
- If S is infinite or the number of digits after the decimal point in S is greater than N, only consider the first N decimals after the decimal point in S. Truncate the rest of the digits without performing any kind of rounding.
- If the number of digits after the decimal point in S is less than N, append trailing zeroes to the right side until there are exactly N digits after the decimal point.
- The quality of approximation is the number of digits in the longest common prefix of S and number. The longest common prefix of two numbers is the longest string which is a prefix of the decimal representations of both numbers with no extra leading zeroes. For example, "3.14" is the longest common prefix of 3.1428 and 3.1415.
Constraints
- maxDen will be between 1 and 100,000, inclusive.
- number will contain between 3 and 50 characters, inclusive.
- number will consist of a digit '0', followed by a period ('.'), followed by one or more digits ('0'-'9').
42 "0.141592658" Returns: "1/7 has 3 exact digits"
3 plus the current approximation yields an approximation of Pi.
3 "0.1337" Returns: "0/1 has 1 exact digits"
Not a lot of options here.
80000 "0.1234567891011121314151617181920" Returns: "10/81 has 8 exact digits"
1000 "0.42" Returns: "3/7 has 3 exact digits"
This one can be represented in more than one way. Be sure to choose the one with the lowest denominator. Note that 21/50 is an even more accurate approximation (it is, in fact, exact), but it has the same number of matching digits (all three) and has a greater denominator.
100 "0.420" Returns: "21/50 has 4 exact digits"
All trailing zeros in number are significant.
115 "0.141592658" Returns: "16/113 has 7 exact digits"
A better approximation for the decimal part of Pi.
Submissions are judged against all 204 archived test cases, of which 6 are shown here. Case numbers match the judge’s.
Language: C++17 · define a public class BestApproximationDiv2 with a public method string findFraction(int maxDen, string number) · 204 test cases · 2 s / 256 MB per case