一道简单数学题,要求求出一个分母不超过m的最接近sqrt(n)的分数。
做法就是暴力枚举,注意中间过程不能用浮点数比较,误差要求比较高。
代码如下:
1 #include <cstdio> 2 #include <cstring> 3 #include <algorithm> 4 #include <iostream> 5 #include <cmath> 6 7 using namespace std; 8 9 typedef long long LL; 10 template<class T> T sqr(T x) { return x * x;} 11 template<class T> T gcd(T a, T b) { return b ? gcd(b, a % b) : a;} 12 13 int main() { 14 LL n, m; 15 while (cin >> n >> m) { 16 LL bx = 1, by = 1; 17 // long double r = sqrt((long double) n); 18 // cout << r << endl; 19 for (LL i = 1; i <= m; i++) { 20 LL t = (int) sqrt((double) sqr(i) * n); 21 for (int d = 0; d < 2; d++) { 22 // if (fabs((long double) (t + d) / i - r) < fabs((long double) bx / by - r)) { 23 // bx = t + d, by = i; 24 // } 25 if (abs(sqr(t + d) * sqr(by) - n * sqr(by) * sqr(i)) < abs(sqr(bx) * sqr(i) - n * sqr(by) * sqr(i))) bx = t + d, by = i; 26 } 27 } 28 LL GCD = gcd(bx, by); 29 cout << bx / GCD << "/" << by / GCD << endl; 30 } 31 return 0; 32 }
——written by Lyon