zoukankan      html  css  js  c++  java
  • hdu 2225 The nearest fraction (数学题)

    Problem - 2225

      一道简单数学题,要求求出一个分母不超过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 }
    View Code

    ——written by Lyon

  • 相关阅读:
    Spoj-DWARFLOG Manipulate Dwarfs
    Spoj-DRUIDEOI Fata7y Ya Warda!
    LightOJ1106 Gone Fishing
    LightOJ1125 Divisible Group Sums
    hdu5396 Expression
    cf715B Complete The Graph
    cf601A The Two Routes
    cf602B Approximating a Constant Range
    cf602A Two Bases
    认证方式
  • 原文地址:https://www.cnblogs.com/LyonLys/p/hdu_2225_Lyon.html
Copyright © 2011-2022 走看看