Вычисление больших целых корней Python.
Несмотря на то, что Python изначально поддерживает большие целые числа, извлечение n-го корня из очень больших чисел может привести к ошибке. При работе с такими большими целыми числами вам нужно будет использовать пользовательскую функцию для вычисления n-го корня числа.
def nth_root(x, n):
# Start with some reasonable bounds around the nth root.
upper_bound = 1
while upper_bound ** n <= x:
upper_bound *= 2
lower_bound = upper_bound // 2
# Keep searching for a better result as long as the bounds make sense.
while lower_bound < upper_bound:
mid = (lower_bound + upper_bound) // 2
mid_nth = mid ** n
if lower_bound < mid and mid_nth < x:
lower_bound = mid
elif upper_bound > mid and mid_nth > x:
upper_bound = mid
else:
# Found perfect nth root.
return mid
return mid + 1
x = 2 ** 100
cube = x ** 3
root = nth_root(cube, 3)
x == root
# True
Вычисление больших целых корней
x = 2 ** 100
cube = x ** 3
root = cube ** (1.0 / 3)
OverflowError: long int too large для преобразования в float
Около минуты
12 мая 2022
139 читали