代码之家  ›  专栏  ›  技术社区  ›  Samba Gangineni

python 3中pow(x,y,z)和x**y%z速度的模糊性。哪一个是有效的?

  •  -2
  • Samba Gangineni  · 技术社区  · 7 年前

    结果与预期不符。功率(x,y,z)必须是有效的,但结果发生了变化。为什么?

    import timeit
    print(timeit.timeit("pow(2505626,1520321,2700643)"))
    output:3.700144177302718
    print(timeit.timeit("pow(2505626,1520321,2700643)",number=1000000))
    output:4.591832527890801
    print(timeit.timeit("2505626**1520321%2700643",number=1000000))
    output:0.014752348884940147
    
    1 回复  |  直到 6 年前
        1
  •  0
  •   Nir Alfasi    7 年前

    的确 pow() 在整数上没有很好的性能(以三参数形式)。请参阅函数的docstring:

    代码:

    def pow(*args, **kwargs): # real signature unknown
        """
        Equivalent to x**y (with two arguments) or x**y % z (with three arguments)
    
        Some types, such as ints, are able to use a more efficient algorithm when
        invoked using the three argument form.
        """
        pass