传送门: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
题意:
求不大于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;
}
本篇博客介绍了一道编程题目,目标是找出分母不超过M的情况下,最接近sqrt(N)的分数形式。通过解析题目的核心算法,包括确定分子的方法及如何通过平方差来比较两个分数与sqrt(N)的接近程度。
的分数, 分母最大为m】&spm=1001.2101.3001.5002&articleId=52805205&d=1&t=3&u=fb8353648dbc40d49ac87c4bd23300f4)
3824

被折叠的 条评论
为什么被折叠?



