PAT菜鸡进化史_乙级_1062
一个分数一般写成两个整数相除的形式:N/M
,其中 M 不为0。最简分数是指分子和分母没有公约数的分数表示形式。
现给定两个不相等的正分数 N1/M1
和 N2/M2
,要求你按从小到大的顺序列出它们之间分母为 K 的最简分数。
输入格式:
输入在一行中按 N/M
的格式给出两个正分数,随后是一个正整数分母 K
,其间以空格分隔。题目保证给出的所有整数都不超过 1000。
输出格式:
在一行中按 N/M
的格式列出两个给定分数之间分母为K
的所有最简分数,按从小到大的顺序,其间以 1 个空格分隔。行首尾不得有多余空格。题目保证至少有 1 个输出。
输入样例:
7/18 13/20 12
输出样例:
5/12 7/12
思路:
这题不难哒,就是注意一下这里可没说输入的两个分数谁大谁小哦!这个得自己调整一下~
Code:
#include <iostream>
#include <vector>
int gcd(int a, int b);
int main(){
using namespace std;
// input the original data
int N1, N2, M1, M2, K;
scanf("%d/%d %d/%d %d", &N1, &M1, &N2, &M2, &K);
// calculate the number between the two numbers
if (N1 * M2 > N2 * M1){
swap(N1, N2);
swap(M1, M2);
}
// reduction of fractions to a common denominator to find the bound when the denominator is K
int low = N1 * K / M1 + 1;
int high = !(N2 * K % M2) ? N2 * K / M2 - 1 : N2 * K / M2;
vector<int> output;
for (int i = low; i <= high; i++){
if (gcd(i, K) == 1)
output.push_back(i);
}
// display the result
for (unsigned int i = 0; i < output.size(); i++){
if (i)
cout << " ";
cout << output[i] << '/' << K;
}
return 0;
}
int gcd(int a, int b){
return (b == 0) ? a : gcd(b, a % b);
}