您的位置:首页 > 其它

ACM/ICPC中国·哈尔滨工程大学第八届程序设计竞赛 1006 Find Fractions

2013-04-22 22:26 302 查看
http://acm.hrbeu.edu.cn/index.php?act=problem&id=1006&cid=115

 

 

Find Fractions
TimeLimit: 1 Second   MemoryLimit: 32 Megabyte

Totalsubmit: 69   Accepted: 22  

Description
Consider the fraction, n/d, where n and d are positive integers. If n<d and GCD(n,d)=1, it is called a reduced proper fraction. And GCD(x,y) means the greatest common divisor of x and y.

If we list the set of reduced proper fractions for d ≤ 8 in ascending order of size, we get:

1/8, 1/7, 1/6, 1/5, 1/4, 2/7, 1/3, 3/8, 2/5, 3/7, 1/2, 4/7, 3/5, 5/8, 2/3, 5/7, 3/4, 4/5, 5/6, 6/7, 7/8

It can be seen that 2/5 is the fraction immediately to the left of 3/7.

Our task is to find the fraction immediately to the left of a/b whose denominator does not exceed N.

Input
The first line of the input is a integer T(T ≤ 200), followed by T test cases.

In each test case, there are three integers a, b, N(1≤a<b≤N≤10000 and GCD(a,b)=1) in onw line.

Output
For each test case output the numerator of the fraction which is immediately to the left of a/b and at the same time whose denominator does not exceed N. If there is no such fraction, output -1.

Sample Input
2

3 7 8

1 8 8
Sample Output
2

-1
Source
ACM/ICPC中国·哈尔滨工程大学第八届程序设计竞赛

Submit

Status

 

 

题意:

题目描述:

给出一个最简分数a/b,求在分母小于等于n的情况下,小于a/b且最接近a/b的最简分数,输出这个最简分数的分子;
找不到这样的最简分数的话则输出-1.
 
 
思路 :
假设这个分数为   x/i   
则x/i  > a/b     即x >  a*i /b    
暴力分母i       让x=a*i/b   如果 x与i不互质则x-- 否则就可以认为是一个小于a /b的分数
然后从这些分数中找到离a/b最小的即可
 

代码为同学的:

 

#include<stdio.h>
int num1[10011],num2[10011];
int Gcd(int a,int b)
{
int r;
if(!a || !b)
return 0;
while(b!=0)
{
r=b;
b=a%b;
a=r;
}
return a;
}
int main()
{
int T;
int a,b,n,i;
int tmp,cnt,min_a,min_b;
scanf("%d",&T);
while(T--)
{
scanf("%d%d%d",&a,&b,&n);
cnt=0;
for(i=1;i<=n;i++)//暴力分母
{
tmp=a*i/b;//不能等于它   应该小于他 由于他是取整 如果可以整除的话则tmp--  否则则不需要--了
if(a*i%b==0)
tmp--;
while(Gcd(tmp,i)!=1 && tmp>0)
{
tmp--;
}
if(tmp>0)
{
num1[++cnt]=tmp;//分子
num2[cnt]=i;//分母
}
}
if(cnt<1)
{
printf("-1\n");
continue;
}
min_a=num1[1];  min_b=num2[1];
for(i=2;i<cnt;i++)
{
if(num1[i]*min_b>num2[i]*min_a)
{
min_a=num1[i];
min_b=num2[i];
}
}
printf("%d\n",min_a);
}
return 0;
}


 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐