You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

如何在Python中将非完全平方数的平方根表示为最简根式形式(如√50显示为5√2)

解决方案:将平方根转换为最简根式形式

我来帮你搞定这个需求!要把非完全平方数的平方根转换成最简根式(比如把√300变成10√3),核心思路是找到该数的最大完全平方因子,然后将其开方后提取到根号外面。下面是修改后的完整Python代码,完美实现了你要的功能:

import math

def simplify_square_root(num):
    # 获取num的整数平方根(小于等于num平方根的最大整数)
    max_factor = math.isqrt(num)
    # 从最大可能的因子往下找,找到第一个平方能整除num的数
    for i in range(max_factor, 0, -1):
        if num % (i * i) == 0:
            radicand = num // (i * i)
            # 根据系数是否为1返回不同格式
            if i == 1:
                return f"√{radicand}"
            else:
                return f"{i}√{radicand}"
    # 理论上不会走到这里,因为i=1时一定满足条件
    return f"√{num}"

# 主程序逻辑
try:
    num = int(input("Enter the number for which you want the square root: "))
    if num < 0:
        print("The square root of the given number is imaginary")
    else:
        # 判断是否为完全平方数
        sqrt_num = math.isqrt(num)
        if sqrt_num * sqrt_num == num:
            print(f"The given number is perfect square and the square root is {sqrt_num} ")
        else:
            simplified = simplify_square_root(num)
            print(f"The square root of the given number is {simplified}")
except ValueError:
    print("Please enter a valid integer!")

代码说明:

  1. 新增的化简函数simplify_square_root

    • math.isqrt()(Python 3.8+支持)获取num的整数平方根,从这个最大值开始向下遍历,确保能找到最大的完全平方因子,这样化简后的结果就是最简形式。
    • 找到符合条件的因子后,计算根号内剩余的数radicand,再根据提取的系数是否为1,返回对应的根式格式(比如系数为1时只显示√x,系数大于1时显示i√x)。
  2. 优化了完全平方数的判断

    • 原来的math.floor(math.sqrt(num)) == math.ceil(math.sqrt(num))依赖浮点数运算,对于极大的整数可能存在精度问题。改用math.isqrt(num) * math.isqrt(num) == num的方式,完全用整数运算判断,更准确可靠。
  3. 增加了异常处理

    • 加入try-except块,防止用户输入非整数时程序崩溃,提升了鲁棒性。

测试案例:

  • 输入300 → 输出The square root of the given number is 10√3
  • 输入12 → 输出The square root of the given number is 2√3
  • 输入7 → 输出The square root of the given number is √7
  • 输入25 → 输出The given number is perfect square and the square root is 5
  • 输入-9 → 输出The square root of the given number is imaginary

内容的提问来源于stack exchange,提问作者Jaskirat Singh Maskeen

火山引擎 最新活动