Giai thừa của n (ký hiệu n!) là tích các số nguyên dương từ 1 đến n. Định nghĩa: 0! = 1, n! = n × (n-1)!.
Thuật toán lặp (Iterative) - khuyên dùng
int Factorial(int n) {
if (n < 0) throw new ArgumentException("n phải >= 0");
int result = 1;
for (int i = 2; i <= n; i++) {
result *= i;
}
return result;
}
Mã nguồn ví dụ (while loop)
using System;
namespace MyApplication {
class Factorial {
public int Calculate(int n) {
int result = 1;
while (n != 1) {
result *= n;
n--;
}
return result;
}
static void Main(string[] args) {
int value = 5;
Factorial fact = new Factorial();
int ret = fact.Calculate(value);
Console.WriteLine("Giá trị: {0}", ret); // 120
Console.ReadLine();
}
}
}
Kết quả
Giá trị: 120
Phiên bản đệ quy (Recursive)
int FactorialRecursive(int n) {
if (n <= 1) return 1;
return n * FactorialRecursive(n - 1);
}
So sánh
| Phương pháp | Stack | Hiệu năng | Giới hạn n (int) |
|---|---|---|---|
| Iterative (for/while) | O(1) | Nhanh nhất | 12 (12! = 479M < 2.14B) |
| Recursive | O(n) | Chậm hơn (function call overhead) | 12 (cùng giới hạn int) |
Xử lý số lớn (BigInteger)
using System.Numerics;
BigInteger FactorialBig(int n) {
BigInteger result = 1;
for (int i = 2; i <= n; i++) result *= i;
return result;
}
// 20! = 2432902008176640000 (vượt long)
Console.WriteLine(FactorialBig(20));
Lưu ý
- Code gốc dùng
while (n != 1)— sai chon = 0(vòng lặp vô hạn). Nên dùngfor (int i=2; i<=n; i++)hoặc checkn <= 1trước. int32-bit chỉ chứa đến 12! (479,001,600). 13! = 6,227,020,800 > int.MaxValue → overflow.- Dùng
long(64-bit) đến 20!. Lớn hơn →BigInteger. - Trong thực tế: cache bảng lookup cho n ≤ 20.