फैक्टोरियल (n!) एक गैर-ऋणात्मक पूर्णांक n के लिए 1 से n तक सभी धनात्मक पूर्णांकों का गुणनफल होता है।
परिभाषा
n! = n × (n-1) × (n-2) × ... × 2 × 1
0! = 1 (परिभाषा द्वारा)
इटरेटिव दृष्टिकोण (while लूप)
int result = 1;
while (n != 1) {
result = result * n;
n = n - 1;
}
उदाहरण
using System;
namespace MyApplication {
class Factorial {
public int Calculate(int n) {
int result = 1;
while (n != 1) {
result = result * n;
n = n - 1;
}
return result;
}
static void Main(string[] args) {
int value = 5;
Factorial fact = new Factorial();
int ret = fact.Calculate(value);
Console.WriteLine("Value is : {0}", ret);
Console.ReadLine();
}
}
}
आउटपुट
Value is : 120
चरण-दर-चरण (5! के लिए)
| इटरेशन |
n |
result (पहले) |
result = result * n |
| 1 |
5 |
1 |
5 |
| 2 |
4 |
5 |
20 |
| 3 |
3 |
20 |
60 |
| 4 |
2 |
60 |
120 |
| 5 |
1 |
120 |
लूप समाप्त |
रिकर्सिव दृष्टिकोण
public static long FactorialRecursive(int n) {
if (n <= 1) return 1;
return n * FactorialRecursive(n - 1);
}
बड़ी संख्याओं के लिए: BigInteger
using System.Numerics;
public static BigInteger FactorialBig(int n) {
BigInteger result = 1;
for (int i = 2; i <= n; i++) {
result *= i;
}
return result;
}
// 20! = 2,432,902,008,176,640,000 (64-बिट से बड़ा)
// 100! में 158 अंक होते हैं
फंक्शनल/LINQ दृष्टिकोण
using System.Linq;
public static long FactorialLinq(int n) {
return Enumerable.Range(1, n).Aggregate(1L, (acc, x) => acc * x);
}
ओवरफ्लो सावधानी
| टाइप |
अधिकतम n |
अधिकतम मान |
int (32-बिट) |
12 |
479,001,600 |
long (64-बिट) |
20 |
2,432,902,008,176,640,000 |
BigInteger |
असीमित (मेमोरी तक) |
कोई सीमा नहीं |
मुख्य बिंदु
- इटरेटिव दृष्टिकोण रिकर्सिव से अधिक मेमोरी-कुशल है (स्टैक ओवरफ्लो नहीं)।
- 20! से बड़ी संख्याओं के लिए
BigInteger आवश्यक।
- फैक्टोरियल बहुत तेजी से बढ़ता है - प्रैक्टिकल उपयोग सीमित है।
- कॉम्बिनेटोरिक्स, प्रायिकता, टेलर श्रृंखला में उपयोगी।