Cluj München 1140km

Gânduri clujene din Bavaria

München - Munich - Monaco di Baviera

3. martie 2009 20:01
by skorpionking
0 Comentarii

.NET 60 seconds code: Factorial C#

3. martie 2009 20:01 by skorpionking | 0 Comentarii

Here are 3 ways to compute the factorial n!:

// Recursion - factorial recursiv
static int fact(int n)
{           
 if (n <= 1) return 1;
        return n * fact(n - 1);
}

//Iterative - factorial iterativ
static int fact(int n)
{           
 int sum = 1;           
 if (n <= 1) return sum;           
 while (n > 1)           
 {               
  sum *= n;               
  n--;           
 }           
 return sum;
}


// C# 3.x way - factorial in C# 3.x cu delegates si functii anonime
Func<int,int> fact = null;
fact = n => n <= 1 ? 1 : n * fact(n-1);


Life is good! Happy programming!

Adaugă comentariu

biuquote
Loading