● 문제출처
https://swexpertacademy.com/main/code/problem/problemDetail.do
●정리(요약)
N, M이 주어질 때, N의 M 거듭제곱 값을 구하는 프로그램을 재귀호출을 이용하여 구현해 보아라.
+BufferedReader, StringTokenizer, StringBuilder 등 사용 X
즉, java: import java.util.Scanner; 만 사용
●코드 1
import java.util.Scanner;
class Solution
{
public static void main(String args[])throws Exception{
Scanner sc = new Scanner(System.in);
for(int i =1; i<=10; i++) {
int seq = sc.nextInt();
long N = sc.nextLong();
int M = sc.nextInt();
long result= pow(N,N,M-1);
System.out.println("#"+seq+" "+result);
}
}
public static long pow(long now ,long N, int M) {
if(M==0) {
return now;
}
return pow(now*N,N,M-1);
}
}
● 코드 2
import java.util.Scanner;
class Solution
{
public static void main(String[] args) throws Exception{
Scanner sc = new Scanner(System.in);
for(int i =1; i<=10; i++) {
int seq = sc.nextInt();
long N = sc.nextLong();
int M = sc.nextInt();
long result= pow(N,M-1);
System.out.println("#"+seq+" "+result);
}
}
public static long pow(long N, int M) {
if(M==0) {
return N;
}
return N*pow(N,M-1);
}
}
● 느낀점
코드 1, 2 차이점은 크게 없다.
재귀 호출을 이용하는 간단한 문제여서 D3가 맞나 싶을 정도로 5분도 안 걸린 거 같다.