Post

[BOJ] 1629. ๊ณฑ์…ˆ(python)

๐Ÿ“Œ๋ฌธ์ œ

Alt text

๐Ÿ’ช์•„์ด๋””์–ด

๋‚ด์žฅํ•จ์ˆ˜ pow()๋กœ ๊ฑฐ๋“ญ์ œ๊ณฑ์„ ๊ตฌํ˜„ํ•  ๊ฒฝ์šฐ ์‹œ๊ฐ„๋ณต์žก๋„๊ฐ€ O(N)์ด๋‹ค. N์ด 1e6์ด๊ธฐ ๋•Œ๋ฌธ์— O(logN)์˜ ์•Œ๊ณ ๋ฆฌ์ฆ˜์„ ๊ตฌํ˜„ํ•ด์•ผํ•œ๋‹ค.

\[f(a,b) = \begin{cases} a^{b//2}\ * \ a^{b//2}, & \text{if b is even} \\ a^{b//2}\ * \ a^{b//2} \ * \ a, & \text{if b is odd} \end{cases}\]


์ด ์žฌ๊ท€ํ•จ์ˆ˜๋Š” b//2๋ฅผ ํ•˜๋ฉด์„œ b==0์ด ๋˜๋ฉด ์ข…๋ฃŒ๋œ๋‹ค.

๐Ÿฅ‚์ฝ”๋“œ

1
2
3
4
5
6
7
8
9
10
import sys; input = sys.stdin.readline
a, b, c = map(int,input().split())

answer = 1
while b > 0:
    if b % 2 != 0:
        answer = (answer * a) % c
    b //= 2
    a = (a * a) % c
print(answer)
This post is licensed under CC BY 4.0 by the author.

Comments powered by Disqus.