Problem:
Ordered Fractions
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
———————————————————————————————————————————————————————————————————————
My Answer:
/*
ID:iby071
LANG:C++
TASK:frac1
*/
#include<iostream>
#include<fstream>
using namespace std;
struct frac
{ friend bool operator<(frac,frac);
int a;
int b;
frac(int n1=0,int n2=0):a(n1),b(n2){}
};
bool operator<(frac f1,frac f2) //定义分数大小的比较
{ if(f1.a*f2.b<f1.b*f2.a) return true;
else return false;
}
int divide(int low,int high,frac f[])
{ frac k=f[low];
do
{ while(low<high && k<f[high]) --high;
if(low<high) {f[low]=f[high];++low;}
while(low<high && f[low]<k) ++low;
if(low<high) {f[high]=f[low];--high;}
}while(low!=high);
f[low]=k;
return low;
}
void quickSort(int low,int high,frac f[])
{ if(low>=high) return;
int mid=divide(low,high,f);
quickSort(low,mid-1,f);
quickSort(mid+1,high,f);
}
int gcd(int a,int b) //背下来:辗转相除法(by欧几里得)求最大公约数!
{ if(b==0)
return a;
else
return gcd(b,a%b);
}
bool check(int a,int b) //判断是否最简分数
{ if(gcd(a,b)==1) return true;
else return false;
}
int main()
{ ifstream fin("frac1.in");
ofstream fout("frac1.out");
int n,size=0;
frac *f;
fin>>n;
f=new frac[n*(n-1)/2+2];
f[0]=frac(0,1); //特别的:0/0
++size;
for(int b=n;b>1;--b)
for(int a=1;a<b;++a)
if(check(a,b)) {f[size]=frac(a,b);++size;}
f[size]=frac(1,1); //特别的:1/1
++size;
quickSort(0,size-1,f);
for(int i=0;i<size;++i)
fout<<f[i].a<<'/'<<f[i].b<<endl;
return 0;
}