Bert is a programmer with a real fear of floating point arithmetic. Bert has quite successfully used rational numbers to write his programs but he does not like it when the denominator grows large. Your task is to help Bert by writing a program that decreases the denominator of a rational number, whilst introducing the smallest error possible. For a rational number A/B, where B > 2 and 0 < A < B, your program needs to identify a rational number C/D such that: 
1. 0 < C < D < B, and 
2. the error |A/B - C/D| is the minimum over all possible values of C and D, and 
3. D is the smallest such positive integer.

InputThe input starts with an integer K (1 <= K <= 1000) that represents the number of cases on a line by itself. Each of the following K lines describes one of the cases and consists of a fraction formatted as two integers, A and B, separated by “/” such that: 
1. B is a 32 bit integer strictly greater than 2, and 
2. 0 < A < BOutputFor each case, the output consists of a fraction on a line by itself. The fraction should be formatted as two integers separated by “/”.Sample Input

3
1/4
2/3
13/21

Sample Output

1/3
1/2
8/13

题意:给定分数A/B,求C/D(满足D<B),使得C/D最接近A/B。

思路:可以用扩展欧几里德解决。这里是新认识了一种利用“连分数”来解决的做法。

连分数将A/B表示为一连续的分数=1/(B/A+B%A),然后B%A又继续递推,直到A=1,这时令B=B-1,然后带回这个连分数,就可以得到最接近的分数。

(如果是令B=B+1,得到的分数更接近A/B,但是不满足D<B。

(连分数还可以求把X开根号表示为分数。

#include<bits/stdc++.h>
using namespace std;
int a[],num;
void solve(int x,int y)
{
num=; int t;
while(x!=){
a[++num]=y/x;
t=x; x=y%x; y=t;
}
int C=,D=y-;
while(num>=){
t=D;D=a[num]*D+C;C=t;
num--;
}
printf("%d/%d\n",C,D);
}
int main()
{
int T,A,B,i,j;
scanf("%d",&T);
while(T--){
scanf("%d/%d",&A,&B);
int g=__gcd(A,B);
if(A==) printf("%d/%d\n",A,B-);
else if(g>) printf("%d/%d\n",A/g,B/g);
else solve(A,B);
}
return ;
}

最新文章

  1. 项目前端技术-learn
  2. .NET DLL 保护措施详解(二)关于性能的测试
  3. hibernate----hibernate的基础设置
  4. swift之元组类型
  5. Application路径
  6. Swift中可选型的Optional Chaining 和 Nil-Coalesce(Swift2.1)
  7. 面试题25:最小的K个数
  8. UITabBarController详细说明(简介和设置)
  9. Poj Roadblocks(次短路)
  10. ubuntu上的mysql数据库双机备份设置
  11. Best Grass
  12. WebService--jax
  13. 下载 mysql 数据库 的步骤 完整版
  14. 老是上不了 google scholar...
  15. 安装 VS2017 的正确姿势
  16. EF 事务(非分布式事务)
  17. 七、Spring Boot 启动配置原理
  18. mac 安装Seaslog扩展及SeasLogger应用
  19. Why is IMAP better than POP?
  20. Window下Neo4j安装教程

热门文章

  1. curl抓取数据
  2. 用canal监控binlog并实现mysql定制同步数据的功能
  3. sqlplus登陆scott用户,以及退出连接
  4. 转:c++ 11 新特性
  5. AppCompatActivity
  6. SolidEdge 如何绘制零件图的剖视图
  7. SolidEdge 如何绘制断裂剖视图 局部剖视图
  8. sql 导入数据库 出现乱码问题 解决办法 设置 --default-character-set=utf8
  9. CSDN-markdown编辑器之从线上导入Markdown文件
  10. XML语法笔记