[Swust OJ 801]--Ordered Fractions

题目链接:http://acm.swust.edu.cn/problem/801/

Time limit(ms): 1000      Memory limit(kb): 10000
 
Description

Consider the set of all reduced fractions between 0 and 1 inclusive with denominators less than or equal to N.

Here is the set when N = 5:

0/1 1/5 1/4 1/3 2/5 1/2 3/5 2/3 3/4 4/5 1/1

Write a program that, given an integer N between 1 and 160 inclusive, prints the fractions in order of increasing magnitude.

Input

One line with a single integer N.

 

Output

One fraction per line, sorted in order of magnitude.

 
Sample Input
5

 
Sample Output
0/1
1/5
1/4
1/3
2/5
1/2
3/5
2/3
3/4
4/5
1/1

 
 
题目大意:给定一个数,代表分母的最大值,从小到大,输出所有分母小于N,值小于等于1的所有分数
直接上代码:
 1 #include <iostream>
 2 #include <algorithm>
 3 #include <cstdio>
 4 #define maxn 1000010
 5 using namespace std;
 6 struct node{
 7     int x, y;
 8     bool operator<(const node &tmp)const{
 9         if (x != tmp.x)
10             return x*tmp.y < y*tmp.x;
11         return y > tmp.y;
12     }
13 }a[maxn];
14 int gcd(int a, int b){
15     return !b ? a : gcd(b, a%b);
16 }
17 int main(){
18     int n, i, j;
19     while (~scanf("%d", &n)){
20         int pos = 0;
21         //i代表分母,j代表分子
22         for (i = 1; i <= n; i++){
23             for (j = 0; j <= i; j++){
24                 if (!j&&i != 1) continue;
25                 if (gcd(j, i) == 1){
26                     a[pos].x = j;
27                     a[pos++].y = i;//  x/y
28                 }
29             }
30         }
31         sort(a, a + pos);
32         for (i = 0; i < pos; i++)
33             printf("%d/%d
", a[i].x, a[i].y);
34     }
35     return 0;
36 }
View Code
原文地址:https://www.cnblogs.com/zyxStar/p/4593271.html