【HDU 2225】【数学题 构造】【求不大于sqrt(n)的分数, 分母最大为m】

本篇博客介绍了一道编程题目,目标是找出分母不超过M的情况下,最接近sqrt(N)的分数形式。通过解析题目的核心算法,包括确定分子的方法及如何通过平方差来比较两个分数与sqrt(N)的接近程度。

传送门:HDU2225

描述:

The nearest fraction

Time Limit: 1000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 645    Accepted Submission(s): 135


Problem Description
Find the fraction closest to sqrt(N), the denominator of the fraction is no more than M.
 

Input
The input consists of multiple test cases.For each case the input contains two integers N and M, 1<=N<=1000000, 1<=M<=1000.
 

Output
For each case output one line, contaning the fraction that in the form "A/B" where A and B are positive integers with no common factors greater than one.
 

Sample Input
  
9 4
 

Sample Output
  
3/1
 

Author
8600
 

Recommend
lcy   |   We have carefully selected several similar problems for you:   2224  2226  2227  2228  2229 


题意:

求不大于sqrt(n)的分数, 分母最大为m

思路:

所以这个以i为分母的分子一定是sqrt(i*i*n)或sqrt(i*i*n)+1。所以遍历所以i找到那个最接近的分数。
这里比较两个分数谁更接近sqrt(n)时,将sqrt(n)平方,然后平方做差(防止出现精度问题),然后比较(t+d)^2/i^2-n,x^2/y^2-n的大小

代码:

 #include <bits/stdc++.h>
#define ll __int64
using  namespace  std;

template<class T> T sqr(T x){ return x * x; }
template<class T> T gcd(T a, T b){ return b ? gcd(b, a%b) : a; }
ll n,m;

int  main(){
  while(cin>>n>>m){
    ll x=1,y=1;//x/y
    for(int i=1; i<=m; i++){
      ll t=(ll)sqrt((double)sqr(i) * n);
      for(int d=0; d<=1; d++){
        if(abs(sqr(t + d) * sqr(y)- n * sqr(i) * sqr(y)) < abs(sqr(x) * sqr(i)- n * sqr(i) * sqr(y)))
          x = t + d, y = i;
      }
    }
    ll div = gcd(x, y);
    cout<<x/div<<"/"<<y/div<<endl;
  }
  return 0;
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值