题解 P1226 【【模板】快速幂||取余运算】

智子

2019-04-22 10:33:24

Solution

看到题解里貌似并没有Python的题解,我来发一个,共两行。 众所周知,为什么有时候洛谷er们要用Python呢?因为Python里已经包装了很多算法,用在OI中基本上等于打游戏时开外挂。虽然 对于这道题,Python 3中有一个数学函数pow(),它在help()函数中的说明是这样的: ```python pow(x, y, z=None, /) 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. ``` `x**y % z`,这正好就是这道题所用到的算法,所以直接调用`pow(b, p, k)`就OK了。一般来说,编程语言本身的库函数都会往死里优化,基本上不用担心时间复杂度的问题。(除了某些特别坑的) 最后要注意的一点就是,很多人提交Python都莫名RE,原因是Python 3的`input()`函数返回的是字符串,必须用`int()`转换为整数。如果一行有多个数字,则调用`split()`方法分割成多个字符串。 上代码: ```python a = input().split() print(a[0] + '^' + a[1] + ' mod ' + a[2] + '=' + str(pow(int(a[0]), int(a[1]), int(a[2])))) ```