calculate mod using pow function python

2019-02-13 13:39发布

So, If i would like to calculate the value of 6^8 mod 5 using the pow function, what should I put in a line??

In the assumption that You don't need to import it first

I know that pow is used like pow (x, y) = pow (6, 8) = 6^8 and

My guess is

mod.pow(6,8)

Thank you!

标签: python pow
3条回答
做个烂人
2楼-- · 2019-02-13 13:46

It's simple: pow takes an optional 3rd argument for the modulus.

From the docs:

pow(x, y[, z])

Return x to the power y; if z is present, return x to the power y, modulo z (computed more efficiently than pow(x, y) % z). The two-argument form pow(x, y) is equivalent to using the power operator: x**y.

So you want:

pow(6, 8, 5)

Not only is pow(x, y, z) faster & more efficient than (x ** y) % z it can easily handle large values of y without using arbitrary precision arithmetic, assuming z is a simple machine integer.

查看更多
We Are One
3楼-- · 2019-02-13 13:48

check the docs of pow:

pow(6, 8, 5)

does what you want.

do not use a ** b % n! while this will give the correct result it will be by orders of magnitude slower if you do calculations for bigger numbers. pow will do the modulo operation in every step while ** will first do the exponentiation in the integers (which may result in a huge number) and take the modulus only at the end.

now if you are interested in numbers that are bigger than 32 bit you may want to have a look at gmpy2 for even more speed.

查看更多
虎瘦雄心在
4楼-- · 2019-02-13 13:48

You can use '%' character to get the modulo value. For example print(pow(6,8) % 5) or print(6**8 % 5).

查看更多
登录 后发表回答