The factorial of a non-negative integer 𝑛 n is the product of all positive integers less than or equal t 𝑛. It is denoted by 𝑛!.
Definition n!=n×(n−1)×(n−2)×…×2×1
Examples
5!=5×4×3×2×1=120
3!=3×2×1=6
1!=1
0!=1
Calculating The Factorial Of A Number
Calculating the factorial of a number in C# can be done using either an iterative or a recursive approach. Here are examples of both methods:
Iterative Approach
using System;
class Program
{
static void Main()
{
Console.Write("Enter a number: ");
int number = int.Parse(Console.ReadLine());
long factorial = Factorial(number);
Console.WriteLine($"Factorial of {number} is {factorial}");
}
static long Factorial(int n)
{
long result = 1;
for (int i = 1; i <= n; i++)
{
result *= i;
}
return result;
}
}
Recursive Approach
using System;
class Program
{
static void Main()
{
Console.Write("Enter a number: ");
int number = int.Parse(Console.ReadLine());
long factorial = Factorial(number);
Console.WriteLine($"Factorial of {number} is {factorial}"); // Result of factoriale
}
static long Factorial(int n)
{
if (n == 0 || n == 1)
return 1;
return n * Factorial(n - 1);
}
}
Explanation
- Iterative Approach: Uses a loop to multiply numbers from 1 to
n
. - Recursive Approach: Calls itself with decremented values until it reaches the base case.
Usage of Factori l Number
You can run either of these programs in a C# environment. Just input a non-negative integer, and it will calculate the factorial. Keep in mind that for larger values of n
, the result can exceed the range of long
, so consider using BigInteger
for very large factorials:
using System;
using System.Numerics;
class Program
{
static void Main()
{
Console.Write("Enter a number: ");
int number = int.Parse(Console.ReadLine());
BigInteger factorial = Factorial(number);
Console.WriteLine($"Factorial of {number} is {factorial}");
}
static BigInteger Factorial(int n)
{
if (n == 0 || n == 1)
return 1;
return n * Factorial(n - 1);
}
}
Thanks
Tags
csharp