๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
Algorithm/๋ฐฑ์ค€(BOJ)

[ ํŒŒ์ด์ฌ(python) ] ๋ฐฑ์ค€ 1009 - ๋ถ„์‚ฐ์ฒ˜๋ฆฌ

by YWTechIT 2021. 6. 7.
728x90

๐Ÿ“ ๋ฐฑ์ค€ 1009 - ๋ถ„์‚ฐ์ฒ˜๋ฆฌ

๋ฐฑ์ค€ 1009 - ๋ถ„์‚ฐ์ฒ˜๋ฆฌ


โšก๏ธ ๋‚˜์˜ ํ’€์ด

๋ฌธ์ œ ์ž์ฒด๋Š” ์–ด๋ ต์ง€ ์•Š์•˜๋‹ค. ๋‹จ์ˆœํ•˜๊ฒŒ a ** b % 10์„ ๊ตฌํ•˜๋ฉด ๋˜๋Š” ๋ฌธ์ œ์˜€๋Š”๋ฐ, 2๊ฐ€์ง€๋ฅผ ์‹ ๊ฒฝ ์“ฐ์ง€ ๋ชปํ–ˆ๋‹ค.

 

  1. ์ •์ˆ˜ b์˜ ๋ฒ”์œ„: 1 <= b < 1,000,000์ธ๋ฐ, ๊ฑฐ๋“ญ์ œ๊ณฑํ˜•ํƒœ๋ผ์„œ ๋‚˜์ค‘์— ๊ฐ’์ด ๊ธฐํ•˜๊ธ‰์ˆ˜์ ์œผ๋กœ ์ปค์ง€๊ฒŒ ๋œ๋‹ค.
  2. a ** b % 10: ๋งŒ์•ฝ, a ** b๊ฐ€ 10์ด ๋‚˜์˜ค๋ฉด 0์ด ์ถœ๋ ฅ๋˜๊ธฐ ๋•Œ๋ฌธ์— ๋”ฐ๋กœ ์กฐ๊ฑด์„ ๋„ฃ์–ด์ค˜์•ผ ํ•œ๋‹ค.

 

1๋ฒˆ์€ ** ๋Œ€์‹  pow ๋‚ด์žฅ ํ•จ์ˆ˜๋ฅผ ์ด์šฉํ–ˆ๋Š”๋ฐ ๊ฒฐ๋ก ์ ์œผ๋กœ x ** y์˜ ์‹œ๊ฐ„ ๋ณต์žก๋„๋Š” O(N)์ด๊ณ , pow(x, y)์˜ ์‹œ๊ฐ„๋ณต์žก๋„๋Š” O(1)์ด๋‹ค. ์™œ ๊ทธ๋Ÿฐ์ง€๋Š” ์Šคํƒ์˜ค๋ฒ„ํ”Œ๋กœ์šฐ ์งˆ๋ฌธ์„ ์ฐธ๊ณ ํ•˜์ž. ๊ทธ๋ฆฌ๊ณ  powํ•จ์ˆ˜์—์„œ ์„ธ ๋ฒˆ์งธ์ธ์ž๊นŒ์ง€ ๋„˜๊ฒจ ์ค„ ์ˆ˜ ์žˆ๋Š”๋ฐ pow(base, -exp, mod) ์„ธ๋ฒˆ์งธ ์ธ์ž๋Š” mod์—ฐ์‚ฐ์„ ํ•  ์ˆ˜ ์žˆ๋‹ค.

 

2๋ฒˆ์€ x % 10๋ฅผ ํ•  ๋•Œ 10 % 10์ด๋ฉด 0์ด ๋˜๋ฏ€๋กœ 0์ผ ๋•Œ๋Š” 10์„ ๋”ํ•ด์ฃผ๋Š” ์กฐ๊ฑด์„ ์ถ”๊ฐ€ํ–ˆ๋‹ค.

 

T = int(input())

for _ in range(T):
    a, b = map(int, input().split())
    result = pow(a, b, 10)
    if not result:
        print(result+10)
    else:
        print(result)

 

์—ฌ๋‹ด์œผ๋กœ x ** y, pow(x, y), math.pow(x, y) ํ•จ์ˆ˜ ์ค‘ ์ œ์ผ ๋น ๋ฅธ ํ•จ์ˆ˜๋Š” math.pow(x, y)์ธ๋ฐ, ๋‹ค์Œ ์ฝ”๋“œ๋ฅผ ํ•œ๋ฒˆ ์‹คํ–‰ํ•˜๋ฉด ๊ณง์žฅ ์•Œ ์ˆ˜ ์žˆ๋‹ค.

 

import timeit

def show_timeit(command, setup):
    print(setup + '; ' + command + ':')
    print(timeit.timeit(command, setup))
    print()

# Comparing small integers
show_timeit('a ** b', 'a = 3; b = 4')
show_timeit('pow(a, b)', 'a = 3; b = 4')
show_timeit('math.pow(a, b)', 'import math; a = 3; b = 4')

# Compare large integers to demonstrate non-constant complexity
show_timeit('a ** b', 'a = 3; b = 400')
show_timeit('pow(a, b)', 'a = 3; b = 400')
show_timeit('math.pow(a, b)', 'import math; a = 3; b = 400')

# Compare floating point to demonstrate O(1) throughout
show_timeit('a ** b', 'a = 3.; b = 400.')
show_timeit('pow(a, b)', 'a = 3.; b = 400.')
show_timeit('math.pow(a, b)', 'import math; a = 3.; b = 400.')
๋ฐ˜์‘ํ˜•

๋Œ“๊ธ€