给定一个整数 N,请你求出所有分母小于或等于 N,大小在 [0,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。
输出格式
按照从小到大的顺序,输出所有满足条件的分数。
每个分数占一行,格式为 a/b,其中 a 为分子, b 为分母。
数据范围
1≤N≤160
输入样例:
5
输出样例:
0/1
1/5
1/4
1/3
2/5
1/2
3/5
2/3
3/4
4/5
1/1
#include <iostream>
#include <cstring>
#include <algorithm>
using namespace std;
int n;
void dfs(int a, int b, int c, int d)
{
if (b + d > n) return;
dfs(a, b, a + c, b + d);
printf("%d/%d\n", a + c, b + d);
dfs(a + c, b + d, c, d);
}
int main()
{
cin >> n;
puts("0/1");
dfs(0, 1, 1, 1);
puts("1/1");
return 0;
}
#include<cstdio>
#include<algorithm>
#include<vector>
using namespace std;
struct Node{
int up, down;
bool operator< (const struct Node &T) const {
return up * T.down < T.up * down;
}
};
vector<Node> v;
int gcd(int a, int b)
{
return b ? gcd(b, a % b) : a;
}
int main()
{
int n;
scanf("%d", &n);
for(int down = 1; down <= n; down ++)
for(int up = 0; up <= down; up ++)
if(gcd(up, down) == 1) v.push_back({up, down});
sort(v.begin(), v.end());//按照值从小到大排序
for(auto &p : v) printf("%d/%d\n", p.up, p.down);
return 0;
}