按形如 a*sqrt(b) 的格式输出一个非负整数的平方根

【题目描述】
输入一个非负整数 x,若能完全开平方根,则输出其对应的整数平方根值。
否则,按形如 a*sqrt(b) 的格式输出其平方根值(a 与 b 均为整数,且 a≠1,b≠1)。

【输入输出】
典型的输入输出样例如下所示:
输入11,输出 sqrt(11);输入25,输出5;输入28,输出 2*sqrt(7)。

cpp 复制代码
/*
in:
0
1
11
25
28

out:
0
1
sqrt(11)
5
2*sqrt(7)
*/

【算法应用】
此代码在 CSP-J 2023 复赛第 3 题中有应用,详见:
https://blog.csdn.net/hnjzsyjyj/article/details/136223796

【算法代码】

cpp 复制代码
#include <bits/stdc++.h>
using namespace std;

void root(int x) {
    if(x==0 || x==1) {
        cout<<x<<endl;
        return;
    }

    int k=1;
    for(int i=2; i*i<=x; i++) { //simply x
        while(x%(i*i)==0) { //get k and x
            k*=i;
            x/=(i*i);
        }
    }

    if(k==1) cout<<"sqrt("<<x<<")"<<endl;
    else if(x==1) cout<<k<<endl;
    else cout<<k<<"*sqrt("<<x<<")"<<endl;
}

int main() {
    int x;
    cin>>x;
    root(x);

    return 0;
}


/*
in:
0
1
11
25
28

out:
0
1
sqrt(11)
5
2*sqrt(7)
*/
相关推荐
小羊失眠啦.17 小时前
Rust核心库(core)深度解析:无依赖基石的设计与实践
数据库·算法·rust
Wenhao.17 小时前
LeetCode Hot100 每日温度
数据结构·算法·leetcode·golang
吃着火锅x唱着歌17 小时前
LeetCode 1679.K和数对的最大数目
算法·leetcode·职场和发展
im_AMBER17 小时前
Leetcode 57
笔记·学习·算法·leetcode
im_AMBER17 小时前
Leetcode 58 | 附:滑动窗口题单
笔记·学习·算法·leetcode
sin_hielo17 小时前
leetcode 2154
算法·leetcode
Sunhen_Qiletian17 小时前
YOLO的再进步---YOLOv3算法详解(上)
算法·yolo·计算机视觉
ANYOLY18 小时前
Sentinel 限流算法详解
算法·sentinel
No0d1es19 小时前
电子学会青少年软件编程(C/C++)六级等级考试真题试卷(2025年9月)
c语言·c++·算法·青少年编程·图形化编程·六级
AndrewHZ19 小时前
【图像处理基石】图像去雾算法入门(2025年版)
图像处理·人工智能·python·算法·transformer·cv·图像去雾