- 问题描述
输入一个自然数N,请写一个程序来增序输出分母小于等于N的既约真分数(即无法再进行约分的小于1的分数) - 输入说明
单独的一行,一个自然数N(1...20) - 输出说明
每个分数单独占一行
按照分数大小升序排列
对于分子为0的分数,仅输出0/1,不输出其它分母的分数,比如0/2, 0/3。
- 输入范例
cpp
4
- 输出范例
cpp
0/1
1/4
1/3
1/2
2/3
3/4
感想:构造真约数string 类型,把真约数装vector里,再真约数排序;输出即可。
代码如下:
cpp
#include <bits/stdc++.h>
using namespace std;
//比较真约数的大小,降序排序
bool compare(const string &a,const string &b) {
auto pos_left = a.find('/');
auto pos_right = b.find('/');
int left_numerator = stoi(a.substr(0,pos_left));//左边真约数的分子
int left_denominator = stoi(a.substr(pos_left+1));//左边真约数的分母
int right_numerator = stoi(b.substr(0,pos_right));//右边真约数的分子
int right_denominator = stoi(b.substr(pos_right+1));//右边真约数的分母
return left_numerator*right_denominator<left_denominator*right_numerator;
}
bool commonDivisor(const string &s) {
auto pos = s.find('/');
int a = stoi(s.substr(0,pos));
int b = stoi(s.substr(pos+1));
for(int i = 2; i<=a; ++i) {
if(a%i==0 && b%i == 0)
return true;
}
return false;
}
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
int n;
cin >> n;
vector<string> target;
target.push_back("0/1");
for(int i = 1; i<n; ++i) {
for(int j = i+1; j<=n; ++j) {
string temp = to_string(i) +"/"+to_string(j);
if(commonDivisor(temp))
continue;
target.push_back(temp);
}
}
sort(target.begin(),target.end(),compare);
for(string s : target) {
cout<<s<<endl;
}
return 0;
}

