pondelok, 11 október 2021 08:06 Written by 1599 times
Rate this item
(8 votes)

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);
        }



 

 

Last modified on pondelok, 11 október 2021 08:48
Ing.Jaroslav Vadel

Som zakladateľom www.projectik.eu.

Hrám sa na programátora, ktorý ovláda:

c#,cpp,java,unity3d,php,html,NI testand,NI Vision Builder,Cognex In-Sight,NI LabView

"Naprogramovať program, ktorý funguje vie každy. Ale to, že program funguje ešte neznamena, že je napísany správne "

Website: www.projectik.eu