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)/*
ID:******
PROG:frac1
LANG:C++
*/
#include <algorithm>
#include <iostream>
#include <fstream>
using namespace std;
#define N 161
int n;//分母最大值
int coun;//结果规模
struct frac{//分数结构体
int num,deno;
}f[13041];
//重定义比较函数
bool cmp(frac const &a, frac const &b){
return a.num*1.0/a.deno < b.num*1.0/b.deno;
}
//求公约数
int gcd(int a,int b){
if(!b)
return a;
return gcd(b,a%b);
}
//生成符合要求的全部分数(不需排序)
void getfraction(){
coun = 0;
f[coun].num = 0;
f[coun].deno = 1;
coun ++;
f[coun].num = 1;
f[coun].deno = 1;
coun ++;
for(int i = 2;i <= n; i++)
for(int j = 1;j < i;j ++)
if(gcd(i,j) == 1){
f[coun].num = j;
f[coun].deno = i;
coun ++;
}
}
int main(){
ofstream fout ("frac1.out");
ifstream fin ("frac1.in");
fin >> n;
getfraction();
sort(f,f+coun,cmp);//递增排序
for(int i = 0;i < coun;i ++)
fout<<f[i].num<<'/'<<f[i].deno<<endl;
return 0;
}
/*
ID:******
PROG:frac1
LANG:C++
*/
#include <algorithm>
#include <iostream>
#include <fstream>
using namespace std;
#define N 161
int n;//分母最大值
int coun;//结果规模
struct frac{//分数结构体
int num,deno;
}f[13041];
//重定义比较函数
bool cmp(frac const &a, frac const &b){
return a.num*1.0/a.deno < b.num*1.0/b.deno;
}
//求公约数
int gcd(int a,int b){
if(!b)
return a;
return gcd(b,a%b);
}
//生成符合要求的全部分数(不需排序)
void getfraction(){
coun = 0;
f[coun].num = 0;
f[coun].deno = 1;
coun ++;
f[coun].num = 1;
f[coun].deno = 1;
coun ++;
for(int i = 2;i <= n; i++)
for(int j = 1;j < i;j ++)
if(gcd(i,j) == 1){
f[coun].num = j;
f[coun].deno = i;
coun ++;
}
}
int main(){
ofstream fout ("frac1.out");
ifstream fin ("frac1.in");
fin >> n;
getfraction();
sort(f,f+coun,cmp);//递增排序
for(int i = 0;i < coun;i ++)
fout<<f[i].num<<'/'<<f[i].deno<<endl;
return 0;
}
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