JAVA

24. 재귀호출 거듭제곱

NamGH 2023. 8. 2. 16:25
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("숫자1: ");
int a = sc.nextInt();
System.out.print("숫자2: ");
int b = sc.nextInt();
System.out.println(a + "의 " + b + "승: " + num(a,b));
//숫자 3 숫자 2 = 3x3, 숫자 5 숫자 4 = 5x5x5x5 재귀호출로
}
static int num(int a, int b) {
if(b == 0) {
return 1;
}else {
return a * num(a, b - 1);
}
}

scanner을 이용해 받은 값들을 거듭제곱해주는 식이다 b 즉 숫자 2가 0이되면 멈추고 거듭제곱이기때문에 b에 -1을 하여 거듭제곱식이 되게하였다