C# - Výpočet faktorialu
Faktoriál je funkcia, ktorá priradí každému kladnému celému číslu x také číslo, ktoré sa rovná súčinu všetkých čísel menších alebo rovných x. Definícia faktoriálu:
n! = n * (n -1) * (n - 2) *. . . * 2 * 1
Faktoriál má jeden špeciálny prípad, a to: 0! = 1
Bacha na to: Funkcia faktoriál rastie rýchlejšie, než akákoľvek exponenciálna funkcia. Preto sa vyvarujte vypočtu pre veľke císla.
Priklad 1 - Bez rekurzie [w/o Recursion]:
public static int Factorial(int x)
{
if (x < 0)
{
throw new ArgumentException("The argument is negative ");
}
int result = 1;
for (int i = 2; i <= x; i++)
{
result *= i;
}
return result;
}
Priklad 2 - S rekurziou [ w/ Recursion]:
public static int Factorial(int x)
{
if (x < 0)
{
throw new ArgumentException("The argument is negative ");
}
if (x==0 || x==1)
{
return 1;
}
return x * Factorial(x - 1);
}
Priklad 3 - IEnumerable:
public static IEnumerable<int> Factorial(int x)
{
if (x < 0)
{
throw new ArgumentException("The argument is negative ");
}
if (x == 0)
{
yield return 1;
}
int startIndex = 1;
while (startIndex <= x)
{
yield return startIndex;
startIndex++;
}
}
Priklad 4 = LINQ:
public static int Factorial(int x)
{
return Enumerable.Range(1, x).Aggregate((i, r) => r * i);
}