Để tính lũy thừa 3, đặt power = 3 và áp dụng đệ quy như sau:
if (p != 0) {
return (n * power(n, p - 1));
}
Giả sử số là 5, các lần lặp:
power(5, 3 - 1) // 25
power(5, 2 - 1) // 5
Kết quả trả về 5 * 25 = 125:
Ví dụ
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;
}
}
Kết quả
125