알고리즘
- 수학
- 분할 정복을 이용한 거듭제곱

분할 정복(Divide and Conquer)
- 큰 문제를 작은 단위의 문제로 나누어 해결하고, 그 해답을 합쳐서 전체 문제의 해답을 얻는 알고리즘 설계 기법
- 분할(Divide): 원래의 문제를 작은 크기의 동일한 문제들로 나눈다. 보통 문제를 반으로 쪼개거나, 고르게 나눌 수 있는 다른 방법을 사용한다.
- 정복(Conquer): 작은 문제들을 재귀적으로 해결한다. 만약 작은 문제의 크기가 충분히 작다면, 재귀를 멈추고 문제를 풀 수 있는 직접적인 방법을 사용한다
- 결합(Combine): 작은 문제들의 해답을 결합하여 원래 문제의 해답을 구한다.
long A = in.nextLong();
long B = in.nextLong();
C = in.nextLong();
public static long pow(long A, long exponent) {
if(exponent == 1) {
return A % C;
}
long temp = pow(A, exponent / 2);
if(exponent % 2 == 1) {
return (temp * temp % C) * A % C;
}
return temp * temp % C;
}
System.out.println(pow(A, B));
import java.util.Scanner;
public class Main {
public static long C;
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
long A = in.nextLong();
long B = in.nextLong();
C = in.nextLong();
System.out.println(pow(A, B));
}
public static long pow(long A, long exponent) {
if(exponent == 1) {
return A % C;
}
long temp = pow(A, exponent / 2);
if(exponent % 2 == 1) {
return (temp * temp % C) * A % C;
}
return temp * temp % C;
}
}