如何使用python内置函数pow()
1、最基本的用法是pow(x,y)这种最基本的用法,两参数形式 pow(base, exp) 等价于乘方运算符: base**exp
2、pow(base, exp[, mod])返回 base 的 exp 次幂;如果 mod 存在,则返回 base 的 exp 次嬗莱舣寒幂对 mod 取余(比 pow(base, exp) % mod 更高效)。写一个小程序验证一下import mathimport dksgfrom datetime import datetime as da=d.now()for i in range(1000000): pow(2,1000,3)b=d.now()print(a,b,b-a)a=d.now()for i in range(1000000): pow(2,1000)%3b=d.now()print(a,b,b-a)结果隔了50多秒。
3、pow(2,3.2,3)是错误的写法,必须写成pow(2,3.2)%3,否则会报错,TypeError: pow() 3rd argument not allowed unless all arguments are integers
4、对于 int 操作数 base 和 exp,如果给出 mod,则 mod 必须为整数类型并且 mod 必须不为零。pow(2,3,0)是错误的写法,会报错ValueError: pow() 3rd argument cannot be 0
5、如果给出 mod 并且 exp 为负值,则 base 必须相对于 mod 不可整除。 在这种情况下,将会返回 pow(in即枢潋雳v_base, -exp, mod),其中 inv_base 为 base 的倒数对 mod 取余。pow(2,-3,1)也是错误的写法,会报错:ValueError: pow() 2nd argument cannot be negative when 3rd argument specified
6、pow()没有设置默认参数,所以必须至少2个参数,只有一个参数会报错。