分解代码不适用于大数?

时间:2018-04-09 02:42:42

标签: python

我有一个大的512位数n,我需要将n-1重写为m * 2k 这是我写的代码:     #write(n-1)= m * 2 ^ k(其中m为奇数)

k = 0       # number of times we were able to divide by 2
total = (n-1)                                                                     

while total % 2 == 0:                                                             
    total /= 2                                                                    
    k += 1                                                                        

m = int(total)                                                                                     
assert (n-1) == (2**k) * m          # this does not hold true for large values of n for some reason

问题是它不适用于n的大(515位)值,例如:     8711599454063889217821738854601954834373650047096243407624954758041578156381215983765719390767527065267731131102484447503200895621045535585981917487924709

对于n的上述值,我的代码找到k = 460且m = 2926172291557515

当我在python中评估2926172291557515 * 2 ** 460时,我得到:     8711599454063889889401923055669626316647070894345982715097720460936366477064539266279767451213791729696559357170292404522606916263895951485640687369584640

哪个不等于n-1。有谁知道为什么会发生这种情况?我认为它与拥有如此大的数字有关(这个代码适用于我测试它的较低数字。

2 个答案:

答案 0 :(得分:3)

问题出现是因为您正在使用/=这是浮点除法。将其替换为//=或整数除法,您的代码将起作用。

答案 1 :(得分:3)

@Primusa是正确的。在Python3.x /(或/=)中返回float值,因此失去了很多精度。

>>> n = 8711599454063889217821738854601954834373650047096243407624954758041578156381215983765719390767527065267731131102484447503200895621045535585981917487924709
>>> total = (n-1)
>>> total / 2
4.355799727031945e+153
>>> total // 2
4355799727031944608910869427300977417186825023548121703812477379020789078190607991882859695383763532633865565551242223751600447810522767792990958743962354