3의 거듭제곱의 경우 거듭제곱을 3으로 설정하고 다음 스니펫과 같은 재귀 코드를 적용합니다. -
if (p!=0) {
return (n * power(n, p - 1));
} 숫자가 5라고 가정하면 반복은 -
가 됩니다.power(5, 3 - 1)); // 25 power (5,2-1): // 5
위는 아래와 같이 5*25 즉 125를 반환합니다. -
예
using System;
using System.IO;
public class Demo {
public static void Main(string[] args) {
int n = 5;
int p = 3;
long res;
res = power(n, p);
Console.WriteLine(res);
}
static long power (int n, int p) {
if (p!=0) {
return (n * power(n, p - 1));
}
return 1;
}
} 출력
125