python - 如何计算一个非常大的整数的第 n 个根

标签 python math nth-root

我需要一种方法来计算 Python 中长整数的第 n 个根。

我尝试了 pow(m, 1.0/n),但它不起作用:

OverflowError: long int too large to convert to float

有什么想法吗?

长整数是指真正的长整数,例如:

11968003966030964356885611480383408833172346450467339251 196093144141045683463085291115677488411620264826942334897996389 485046262847265769280883237649461122479734279424416861834396522 819159219215308460065265520143082728303864638821979329804885526 557893649662037092457130509980883789368448042961108430809620626 059287437887495827369474189818588006905358793385574832590121472 680866521970802708379837148646191567765584039175249171110593159 305029014037881475265618958103073425958633163441030267478942720 703134493880117805010891574606323700178176718412858948243785754 898788359757528163558061136758276299059029113119763557411729353 915848889261125855717014320045292143759177464380434854573300054 940683350937992500211758727939459249163046465047204851616590276 724564411037216844005877918224201569391107769029955591465502737 961776799311859881060956465198859727495735498887960494256488224 613682478900505821893815926193600121890632

最佳答案

如果它是一个非常大的数字。你可以使用二分搜索。

def find_invpow(x,n):
    """Finds the integer component of the n'th root of x,
    an integer such that y ** n <= x < (y + 1) ** n.
    """
    high = 1
    while high ** n <= x:
        high *= 2
    low = high/2
    while low < high:
        mid = (low + high) // 2
        if low < mid and mid**n < x:
            low = mid
        elif high > mid and mid**n > x:
            high = mid
        else:
            return mid
    return mid + 1

例如:

>>> x = 237734537465873465
>>> n = 5
>>> y = find_invpow(x,n)
>>> y
2986
>>> y**n <= x <= (y+1)**n
True
>>>
>>> x = 119680039660309643568856114803834088331723464504673392511960931441>
>>> n = 45
>>> y = find_invpow(x,n)
>>> y
227661383982863143360L
>>> y**n <= x < (y+1)**n
True
>>> find_invpow(y**n,n) == y
True
>>>

关于python - 如何计算一个非常大的整数的第 n 个根,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/356090/

相关文章:

python - 使随机像素移动更有效地运行

python - 如何根据特定项目的位置显示结果

algorithm - 如果 g , h 是 f(n) = O(g(n)) 和 g(n) = O(h(n)) 证明 f(n) = O(h(n)) 的函数

c++ - 在 cpp 中计算数字的 n 次根时答案错误

python - 如何在 python 中恢复旧的回溯? (例如倒数第二个)

python - 使用 Python 将文件上传到最新的 MediaWiki 实例的最简单方法?

javascript - 堆叠百分比减少取决于输入(javascript)

javascript - 加速度计 - 球中滚动

algorithm - 整数次根

java - 第 n 个根实现