输入一个自然数N,我们总可以得到一些满足“1≤b≤N,0≤a/b≤1”条件的最简分数a/b(分子和分母互质的分数),请找出所有满足条件的分数。
比方说,当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的两个自然数。
输入包括一个给个给定的自然数N
输出为一个列表,每个分数单独占一行,按照实际大小从小到大排列
样例1
输入:
5
输出:
0/1 1/5 1/4 1/3 2/5 1/2 3/5 2/3 3/4 4/5 1/1
#include <cstdio>
#include <set>
#include <cstring>
#include <iostream>
using namespace std;
struct Node
{
int x,y;
bool operator < (const Node temp)const
{
double a = (double)x/(double)y;
double b = (double)temp.x/(double)temp.y;
return a < b;
}
}node;
int gcd(int a,int b)
{
return b == 0? a:gcd(b,a%b);
}
set <Node> S;
int main()
{
int N;
while(scanf("%d", &N) != EOF)
{
S.clear();
for(int i = 0; i <= N; i++)
for(int j = i+1; j <= N; j++)
{
node.x = i/gcd(i,j);
node.y = j/gcd(i,j);
S.insert(node);
}
node.x = 1;
node.y = 1;
S.insert(node);
for(set<Node>::iterator it = S.begin(); it != S.end(); it++)
printf("%d/%d\n",it->x,it->y);
}
return 0;
}