如何在python中显示50为5√2的平方根



我正在写一个程序来输出一个数字的平方根在python中。我当前的代码如下:

import math
num = int(input("Enter the number for which you want the square root"))
if math.floor(math.sqrt(num)) == math.ceil(math.sqrt(num)):
v = math.sqrt(num)
print(f"The given number is perfect square and the square root is {v} ")
elif num <0:
print("The square root of the given number is imaginary")
else:
print(f"The square root of the given number is u221A{num}") 
#u221A is unicode for square root symbol

我当前的程序检查输入的数字是否是完全平方,然后显示平方根。如果不是完全平方,就会显示√num。例如num = 300,则显示√300。但我想把它显示为10√3。知道怎么做吗。我不希望在我的结果中有任何小数

您可以使用sympy:

import sympy
sympy.init_printing(use_unicode=True)
sympy.sqrt(300)

输出:

10√3

你可以找到你的数的约数的最大根,并将余数表示为√xxx部分:

def root(N):
for r in range(int(N**0.5)+1,1,-1):
if N % (r*r) == 0:
n = N // (r*r)
return str(r) + f"√{n}"*(n>1)
return f"√{N}"

print(root(50)) # 5√2
print(root(81)) # 9
print(root(96)) # 4√6
print(root(97)) # √97

最新更新