【pta】1062 最简分数(涉及求最大公约数)

题目

1062 最简分数

思路

分数比较大小用十字相乘比大小,先找到大于第一个分数的,再限制小于第二个分数。

代码

#include
using namespace std;
int gys(int x, int y)
{
	while (y)
	{
		int t = x%y;
		x = y;
		y = t;
	}
	return x;
}
int main()
{
	int n1, m1, n2, m2,k;
	scanf("%d/%d %d/%d %d", &n1, &m1,&n2,&m2,&k);
	if (n1 * m2 > n2 * m1)
	{
		swap(n1, n2);
		swap(m1, m2);
	}
	int count = 1;
	while(n1 * k >= count * m1)
		count++;
	int flag = 0;
	while (n1 * k < count * m1 && count * m2 < n2 * k)
	{
		if (gys(k, count) == 1)
		{
			if (flag == 0)
			{
				cout << count << "/" << k;
				flag = 1;
			}
			else
			{
				cout << " "<<count << "/" << k;
			}
		}
		count++;
	}
	return 0;
}

你可能感兴趣的:(算法)