Để tìm lũy thừa của một số, trước tiên hãy đặt số đó và lũy thừa -
int n = 15; int p = 2;
Bây giờ, hãy tạo một phương thức và chuyển các giá trị này -
static long power(int n, int p) {
if (p != 0) {
return (n * power(n, p - 1));
}
return 1;
}
Ở trên, cuộc gọi đệ quy đã cho chúng ta kết quả -
n * power(n, p - 1)
Sau đây là toàn bộ mã để có được sức mạnh của một số -
Ví dụ
using System;
using System.IO;
public class Demo {
public static void Main(string[] args) {
int n = 15;
int p = 2;
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;
}
} Đầu ra
225