按形如 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)
*/
相关推荐
不会就选b2 小时前
算法日常・每日刷题--<贪心>14
算法
mmmmath_34 小时前
LeetCode.541.反转字符串II
数据结构·算法·leetcode
Navigator_Z5 小时前
LeetCode //MySQL - 1251. Average Selling Price
c语言·算法·leetcode
醇氧6 小时前
MySQL 8.0 系统表损坏与引擎转换故障排查实战
数据结构·算法
大熊背6 小时前
《Color constancy by characterization of illumination chromaticity》之色度色域最大化算法(二)
算法·白平衡·色度·色温
钓鱼的肝6 小时前
梳理(1-5)
c++·经验分享·笔记·算法·青少年编程
HZZD_HZZD6 小时前
CSDN_批发市场水电漏损归因算法LAM的原理与落地
嵌入式硬件·物联网·算法
shirsl8 小时前
算法 Day 5 树 / 二叉树 + DFS
数据结构·python·算法
木子算法9 小时前
非凸、离散、还耦合:论文里的求解方法是一条四步流水线
人工智能·算法·目标跟踪