按形如 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)
*/
相关推荐
aWty_1 小时前
实分析入门(11)--Cantor三分集
学习·数学·算法·实变函数
兰令水1 小时前
leecodecode【二叉树递归+对称】【2026.6.1打卡-java版本】
算法
地平线开发者9 小时前
profiler debug 工具用法与高一致性策略
算法·自动驾驶
编程大师哥9 小时前
匿名函数 lambda + 高阶函数
java·python·算法
我叫袁小陌10 小时前
算法解题思路指南
算法
地平线开发者10 小时前
Conv+BN+Add+ReLU 融合机制简介
算法·自动驾驶
yuanyuan2o210 小时前
模型预训练:Hugging Face Transformers 基础
算法·ai·语言模型·自然语言处理·nlp·深度优先
杨充10 小时前
1.3 浮点型数据设计灵魂
开发语言·python·算法
妄想出头的工业炼药师11 小时前
GS slam mono
算法·开源