按形如 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)
*/
相关推荐
虾..1 小时前
Linux 简单日志程序
linux·运维·算法
Trent19851 小时前
影楼精修-眼镜祛反光算法详解
图像处理·人工智能·算法·计算机视觉·aigc
蓝色汪洋1 小时前
经典修路问题
开发语言·c++·算法
csuzhucong1 小时前
122魔方、123魔方
算法
Salt_07282 小时前
DAY 40 早停策略和模型权重的保存
人工智能·python·算法·机器学习
卜锦元2 小时前
Golang后端性能优化手册(第三章:代码层面性能优化)
开发语言·数据结构·后端·算法·性能优化·golang
Binky6782 小时前
力扣--回溯篇(2)
算法·leetcode·职场和发展
De-Alf2 小时前
Megatron-LM学习笔记(6)Megatron Model Attention注意力与MLA
笔记·学习·算法·ai
2401_841495643 小时前
【LeetCode刷题】打家劫舍
数据结构·python·算法·leetcode·动态规划·数组·传统dp数组
冰西瓜6003 小时前
STL——vector
数据结构·c++·算法