psotirov

Catalan number

Dec 6th, 2012
91
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 0.88 KB | None | 0 0
  1. using System;
  2. using System.Numerics;
  3.  
  4. class CatalanNumber
  5. {
  6.     static void Main()
  7.     {
  8.         int N = 0;
  9.  
  10.         Console.WriteLine("Catalan number Cn = (2*N)! / (N+1)!*N!");
  11.         Console.Write("Please enter the number N: ");
  12.         if (!int.TryParse(Console.ReadLine(), out N) || N < 0) return;
  13.  
  14.         if (N < 2)
  15.         {
  16.             Console.WriteLine("Catalan number is 1");
  17.             return;
  18.         }
  19.  
  20.         BigInteger nominator = 1;
  21.         BigInteger denominator = 1;
  22.         for (int i = 2; i <= N; i++)
  23.         {
  24.             nominator *= N + i;
  25.             denominator *= i;
  26.             // (2*N)! / (N+1)!*N! = 1.2...N.N+1.N+2...N+N / 1.2...N.N+1 * 1.2...N = N+2.N+3...N+N / 2.3...N
  27.         }
  28.         nominator = nominator / denominator; // the result is always an integer number
  29.         Console.WriteLine("Catalan number is " + nominator);
  30.     }
  31. }
Advertisement
Add Comment
Please, Sign In to add comment