2017-7-15
题目大意
输入一个自然数N,对于一个最简分数a/b(分子和分母互质的分数),满足1<=b<=N,0<=a/b<=1,请找出所有满足条件的分数。
这有一个例子,当N=5时,所有解为:
0/1 1/5 1/4 1/3 2/5 1/2 3/5 2/3 3/4 4/5 1/1
给定一个自然数N,1<=n<=160,请编程按分数值递增的顺序输出所有解。
注:①0和任意自然数的最大公约数就是那个自然数②互质指最大公约数等于1的两个自然数。
题解
枚举所有可能的分数,只要分子和分母的最大公约数是1则记录下来。最后排个序输出一下。
代码
#include <iostream>
#include <fstream>
#include <algorithm>
#include <vector>
#define cin fin
#define cout fout
using namespace std;
ifstream fin("frac1.in");
ofstream fout("frac1.out");
struct Frac {
int a, b;
Frac(int a, int b) {
this->a = a;
this->b = b;
}
};
vector<Frac> frac;
int N;
int gcd(int a, int b) {
while (b) {
int t = b;
b = a%b;
a = t;
}
return a;
}
bool cmp(const Frac &x, const Frac &y) {
return x.a * y.b < y.a * x.b;
}
int main() {
cin >> N;
cout << "0/1" << endl;
for (int i = 1; i <= N; i++) {
for (int j = 1; j < i; j++) {
if (gcd(i, j) == 1) {
frac.push_back(Frac(j, i));
}
}
}
sort(frac.begin(), frac.end(), cmp);
for (int i = 0; i < frac.size(); i++)
cout << frac[i].a << "/" << frac[i].b << endl;
cout << "1/1" << endl;
return 0;
}