按形如 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)
*/
相关推荐
张李浩4 小时前
Leetcode 054螺旋矩阵 采用方向数组解决
算法·leetcode·矩阵
big_rabbit05025 小时前
[算法][力扣101]对称二叉树
数据结构·算法·leetcode
美好的事情能不能发生在我身上5 小时前
Hot100中的:贪心专题
java·数据结构·算法
2301_821700535 小时前
C++编译期多态实现
开发语言·c++·算法
xixihaha13246 小时前
C++与FPGA协同设计
开发语言·c++·算法
小小怪7506 小时前
C++中的函数式编程
开发语言·c++·算法
xixixiLucky6 小时前
编程入门算法题---小明爬楼梯求爬n层台阶一共多少种方法
算法
剑锋所指,所向披靡!6 小时前
数据结构之线性表
数据结构·算法
m0_672703318 小时前
上机练习第49天
数据结构·算法
样例过了就是过了8 小时前
LeetCode热题100 N 皇后
数据结构·c++·算法·leetcode·dfs·深度优先遍历