东华OJ-基础题-120-顺序的分数(C++)

  • 问题描述
    输入一个自然数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;
}


相关推荐
CoovallyAIHub10 小时前
Moonshine:比 Whisper 快 100 倍的端侧语音识别神器,Star 6.6K!
深度学习·算法·计算机视觉
CoovallyAIHub11 小时前
速度暴涨10倍、成本暴降6倍!Mercury 2用扩散取代自回归,重新定义LLM推理速度
深度学习·算法·计算机视觉
CoovallyAIHub12 小时前
实时视觉AI智能体框架来了!Vision Agents 狂揽7K Star,延迟低至30ms,YOLO+Gemini实时联动!
算法·架构·github
CoovallyAIHub12 小时前
开源:YOLO最强对手?D-FINE目标检测与实例分割框架深度解析
人工智能·算法·github
CoovallyAIHub12 小时前
OpenClaw:从“19万星标”到“行业封杀”,这只“赛博龙虾”究竟触动了谁的神经?
算法·架构·github
刀法如飞12 小时前
程序员必须知道的核心算法思想
算法·编程开发·算法思想
徐小夕14 小时前
pxcharts Ultra V2.3更新:多维表一键导出 PDF,渲染兼容性拉满!
vue.js·算法·github
CoovallyAIHub15 小时前
OpenClaw一脚踩碎传统CV?机器终于不再只是看世界
深度学习·算法·计算机视觉
CoovallyAIHub15 小时前
仅凭单目相机实现3D锥桶定位?UNet-RKNet破解自动驾驶锥桶检测难题
深度学习·算法·计算机视觉