• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
LyonLys
愿意在角落唱沙哑的歌 再大声也都是给你 请用心听 不要说话 Contact me via E-mail: lyon.lys@gmail.com
博客园    首页    新随笔    联系   管理    订阅  订阅

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

 

posted @ 2013-07-13 19:43  LyonLys  阅读(206)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3