i,j分別是所求分數的分子分母,對i:0~n和j:i~n進行組合遍歷,檢測當前分數是否知足要求,若是知足,求i / j的值float a,將<a,<i,j> >組合存進map<float,pair<int,int> >中,並按a值對組合排序。而後只需按順序輸出i / j便可。ios
/* ID:jzzlee1 PROG:frac1 LANG:C++ */ #include<iostream> #include<fstream> #include<cmath> #include<map> #include<utility> #include<cstring> using namespace std; ifstream fin("frac1.in"); ofstream fout("frac1.out"); bool check(int i,int j) //檢測分子分母是否知足要求 { if(i==0) { if(j==1) return 1; else return 0; } for(int k=2;k<=i;++k) if(i%k==0&&j%k==0) return 0; return 1; } int main() { int i,j,n;float a; //cin>>n; fin>>n; map<float,pair<int,int> > map1; map<float,pair<int,int> >::iterator iter; for(i=0;i<=n;++i) for(j=i;j<=n;++j) { if(check(i,j)) { a=(float)i/(float)j; map1.insert(make_pair(a,make_pair(i,j))); } } for(iter=map1.begin();iter!=map1.end();++iter) { //cout<<(iter->second).first<<"/"<<(iter->second).second<<endl; fout<<(iter->second).first<<"/"<<(iter->second).second<<endl; } return 0; }