1629 곱셈
문제
자연수 A를 B번 곱한 수를 알고 싶다. 단 구하려는 수가 매우 커질 수 있으므로 이를 C로 나눈 나머지를 구하는 프로그램을 작성하시오.
입력
첫째 줄에 A, B, C가 빈 칸을 사이에 두고 순서대로 주어진다. A, B, C는 모두 2,147,483,647 이하의 자연수이다.
출력
첫째 줄에 A를 B번 곱한 수를 C로 나눈 나머지를 출력한다.
예제 입력 1
예제 출력 1
Solution
Expander
| 12
 3
 4
 5
 6
 7
 8
 9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 
 | import java.util.*
 private var A: Long = 0
 private var B: Long = 0
 private var C: Long = 0
 
 fun main() {
 input()
 solve()
 }
 
 private fun input() = with(Scanner(System.`in`)) {
 A = nextLong()
 B = nextLong()
 C = nextLong()
 }
 
 private fun solve() {
 
 println(calculate(A, B))
 }
 
 private fun calculate(a: Long, b: Long): Long {
 if (b.isOne()) {
 return a.rem(C)
 }
 
 val half = calculate(a, b / 2)
 
 return if (b.isOdd()) {
 ((half * half).rem(C) * a).rem(C)
 } else {
 (half * half).rem(C)
 }
 }
 
 fun Long.isOne() = this.toInt() == 1
 fun Long.isOdd() = this.toInt() % 2 == 1
 
 | 
 
Point of Thinking
- 표현 범위상 Int대신Long을 사용해야 한다.
- 연산을 줄이기 위해서 지수 법칙을 사용하면 타임아웃 없이 연산을 끝낼 수 있다.
- 단, B가 짝수인지 홀수인지에 따라 연산이 다름에 주의해야 한다.
References