Swift Data Structure And Algorithm/Recursive Function
๊ฑฐ๋ญ ์ ๊ณฑ ๊ตฌํ๊ธฐ L
youngjaeLee1026
2022. 4. 7. 16:28
1. ๋ฌธ์
2. ์ ์ถ๋ ฅ
3. ์ ์ถ๋ ฅ ์์
4. ๋ฌธ์ ์ค๊ณ
- ๊ฑฐ๋ญ์ ๊ณฑ์ ๊ฒฝ์ฐ ์ฌ๊ทํจ์, ๋จ์ ์์ ํ์์ผ๋ก ๋ฌธ์ ๋ฅผ ํด๊ฒฐํ ์ ์์ง๋ง, ์ ๋ฌธ์ ์ ํฌ๊ธฐ๋ฅผ ๋ณด๋ฉด m์ด 10^18 ์ด๋ฏ๋ก, O(m)์ ์๊ฐ๋ณต์ก๋๋ก๋ ๋ฌธ์ ๋ฅผ ํด๊ฒฐํ ์ ์์
- ๋ฐ๋ผ์ ์๊ฐ๋ณต์ก๋๋ฅผ ๊ฐ์ ํด์ผ ํ๋๋ฐ, ์ง์์ ๊ฒฝ์ฐ ๊ฑฐ๋ญ ์ ๊ณฑ๋ผ๋ฆฌ ๊ณฑํ๊ฒ ๋๋ฉด ์ง์๋ผ๋ฆฌ๋ ๋ง์ ์ ํ๊ฒ๋๋ ์ฑ์ง์ ์ด์ฉํ๊ฒ ๋๋ฉด ์๊ฐ ๋ณต์ก๋๋ฅผ ์ค์ผ ์ ์์
- m(์ง์)๊ฐ ์ง์์ผ ๊ฒฝ์ฐ๋ n^(m / 2)๋ฅผ ๋๋ฒ ๊ณฑํจ์ผ๋ก์จ n^m์ ๊ตฌํ ์ ์๊ณ , ํ์์ ๊ฒฝ์ฐ n^(m - 1) * n์ ํตํด์ n^m์ ๊ตฌํ ์ ์์
- ๋ฐ๋ผ์ m == 0์ด ๋ ๋ ๊น์ง(๊ธฐ์ ์กฐ๊ฑด) ์ด๋ฅผ ๋ฐ๋ณตํ๊ฒ ๋๋ฉด, O(log m)์ ์๊ฐ๋ณต์ก๋๋ก ๋ฌธ์ ๋ฅผ ํด๊ฒฐํ ์ ์์
5. ์ ์ฒด ์ฝ๋
//MARK: - ๊ฑฐ๋ญ ์ ๊ณฑ ๊ตฌํ๊ธฐ L
//MARK: - Framework
import Foundation
//MARK: Function
func getPowerL(_ n: Int, _ m: Int64) -> Int64 {
if m == 0 {
return 1
}
if m % 2 == 0 {
let result: Int64 = getPowerL(n, m / 2) % 10007
return result * result % 10007
} else {
return Int64(n) * getPowerL(n, m - 1) % 10007
}
}
func solution() -> Void {
//MARK: - Input
guard let input: [String] = readLine()?.components(separatedBy: " ") else { return }
let n: Int = input.map { Int($0) }[0] ?? 0
let m: Int64 = input.map { Int64($0) }[1] ?? 0
var result: Int64 = 0
//MARK: - Process
result = getPowerL(n, m)
//MARK: - Output
print(result)
}
solution()
์ ์ฒด์ฝ๋๋ ์ฌ๊ธฐ์์ ํ์ธํ ์ ์์ต๋๋ค.