Home

C# Example: Combinatorial

 

Introduction

This is an example of a recursive function. It calculates the combinatorial:

using System;

public class Program
{
    static long Factorial(long x)
    {
        if( x <= 1 )
            return 1;
        else
	        return x * Factorial(x - 1);
    }

    static long Combinatorial(long a, long b)
    {
        if( a <= 1 )
            return 1;

        return Factorial(a) / (Factorial(b) * Factorial(a - b));
    }
    
    static int Main()
    {
        const long Number = 5;

        Console.WriteLine("The factorial of {0} is {1}",
		       Number, Factorial(Number));
        Console.WriteLine("The combinatorial of (8, 3) is {0}",
		       Combinatorial(8, 3));

        return 0;
    }
}

This would produce:

The factorial of 5 is 120
The combinatorial of (8, 3) is 56

Press any key to continue . . .
 

Home Copyright © 2007-2013, FunctionX