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.
PROGRAM NAME: frac1
INPUT FORMAT
One line with a single integer N.SAMPLE INPUT (file frac1.in)
5
OUTPUT FORMAT
One fraction per line, sorted in order of magnitude.SAMPLE OUTPUT (file frac1.out)
0/1 1/5 1/4 1/3 2/5 1/2 3/5 2/3 3/4 4/5 1/1思路:枚举各种可能化简后放入set容器中输出即可
/*
ID: youqihe1
PROG: frac1
LANG: C++
*/
#include <iostream>
#include <fstream>
#include <string>
#include <string.h>
#include <set>
using namespace std;
int gcd(int a,int b)
{
return b==0?a:gcd(b,a%b);
}
struct fraction
{
int chi;
int mom;
float val;
bool operator <(const fraction &A)const
{
return val<A.val;
}
};
int main() {
FILE *fin = fopen ("frac1.in", "r");
FILE *fout = fopen ("frac1.out", "w");
int n;
fscanf(fin,"%d",&n);
int i,j,k;
set<fraction>A;
for(i=0;i<=n;i++)
{
for(j=i+1;j<=n;j++)
{
int a=gcd(i,j);
fraction fra;
fra.chi=i/a;
fra.mom=j/a;
fra.val=(float(fra.chi))/(float(fra.mom));
A.insert(fra);
}
}
set<fraction>::iterator it;
for(it=A.begin();it!=A.end();it++)
{
fprintf(fout,"%d/%d\n",it->chi,it->mom);
}
fprintf(fout,"1/1\n");
return 0;
}