python中除法的奇怪行为

Bha*_*rat 9 python math primes floor floor-division

我试图在hackerrank中解决这个问题.在某些时候,我必须检查数字是否除以n(给定输入).

除了一个测试用例(不是问题)之外,这段代码非常有效:

if __name__ == '__main__':
    tc = int(input().strip())
    for i_tc in range(tc):
        n = int(input().strip())
        while n % 2 == 0 and n is not 0:
            n >>= 1
        last = 0



        for i in range(3, int(n ** 0.5), 2):
            while n % i == 0 and n > 0:
                last = n
                n = n // i        # Concentrate here


        print(n if n > 2 else last)
Run Code Online (Sandbox Code Playgroud)

现在你可以看到我只在i是n的因子时除以数字.例如,如果数字是i = 2且n = 4那么n/2和n // 2没有任何区别.

但是当我使用下面的代码时,所有测试用例都会失败:

if __name__ == '__main__':
    tc = int(input().strip())
    for i_tc in range(tc):
        n = int(input().strip())
        while n % 2 == 0 and n is not 0:
            n >>= 1
        last = 0
        for i in range(3, int(n ** 0.5), 2):
            while n % i == 0 and n > 0:
                last = n
                n = n / i      # Notice this is not //
        print(n if n > 2 else last)
Run Code Online (Sandbox Code Playgroud)

这不是第一次.即使对于这个问题,我也遇到了同样的问题.对于这个问题,我必须除以2,所以我使用右移操作符来摆脱这个.但是这里我不能做任何事情,因为正确转移不能帮助我.

为什么会这样?如果数字很小,我看不出任何差异,但随着数字变大,它在某种程度上表现不同.

在/失败时使用//甚至不直观.这是什么原因?

Leo*_*eon 9

之间的差的主要原因n // in / i考虑到ni属于类型的int并且n % i == 0

  1. 类型n // i仍然是,int而类型n / ifloat
  2. Python中的整数具有无限的精度,而浮点数的精度是有限的.

因此,如果值n // i超出了python float类型可以准确表示的范围,那么它将不等于计算值n / i.

插图:

>>> (10**16-2)/2 == (10**16-2)//2
True
>>> (10**17-2)/2 == (10**17-2)//2
False
>>> int((10**17-2)//2)
49999999999999999
>>> int((10**17-2)/2)
50000000000000000
>>> 
Run Code Online (Sandbox Code Playgroud)