Best Rational approximation time limit: 3 Sec memory limit: MB
Submitted by: 297 Resolution: 25
Submitted State [Discussion Version] [Propositional person:Admin] Title Description Many microcontrollers has no floating point unit but does have a (reasonably) fast integer divide unit. In these cases it could pay to the use of rational values to approximate floating point constants. For instance,
355/113 = 3.1415929203539823008849557522124
is a quite good approximation to
π= 3.14159265358979323846
A best rational approximation, p/q, to a real number, X, with denominator at most M are a rational number, p/q (in lowest t erms), with Q <= M such this, for any integers, a and B with B <= M, and A and b relatively prime, p/q are at least a s close to x as A/b:
|x–p/q|≤|x–a/b|
Write a program to compute of the best rational approximation to a real number, X, with denominator at most m. Enter the first Li NE of input contains a single integer P, (1≤p≤1000), which are the number of data sets that follow. Each data set should is processed identically and independently.
Each data set consists of a single line of input. It contains the data set number, K, followed by the maximum denominator value, M (15≤m≤100000), followed by a floating-poi NT value, x, (0≤x < 1). Output for each data set there are a single line of output. The single output line consists of the data set number, K, followed by a single space followed by the numerator, p, of the Best rational approximation to X, followed by a forward slash (/) followed by the denominator, Q, the best rational AP Proximation to x. Sample input
31 100000.1415926535897932382 255.1415926535897932383 15.141592653589793238
Sample output
1 14093/995322 16/1133 1/7
Hint Source
Greater New York Regional Contest 2017
C + + code:
#include <bits/stdc++.h>using namespacestd;intMain () {intp,t,m; Doublex; scanf ("%d",&t); while(t--) {scanf ("%D%D%LF",&p,&m,&x); intA=0, b=1, c=1, d=1, e,f; while(true) {e=a+C; F=b+D; intGcd=__GCD (e,f); E/=gcd;f/=GCD; if(f>m) Break; if(1.0*e/f<=x) {a=e;b=F; } Else{C=e;d=F; }} printf ("%d", p); if(Fabs (1.0*a/b-x) >fabs (1.0*c/d-x)) printf ("%d/%d\n", c,d); Elseprintf ("%d/%d\n", A, b); } return 0;}
Best Rational approximation (Mrs. Fremont series)