Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- * Write a program to calculate the Nth Catalan number by given N.
- *
- * 3 methods included
- */
- using System;
- using System.Diagnostics;
- using System.Numerics;
- class CatalanNumber
- {
- static void Main()
- {
- while (true)
- {
- Stopwatch stopWatch = new Stopwatch();
- BigInteger numberN = InputData();
- stopWatch.Start();
- // FASTEST
- // for N = 100000 , runtime: 00:00:12.90
- BigInteger catalanNumberN = 1;
- BigInteger result = 0;
- for (int i = 1; i <= numberN; i++)
- {
- catalanNumberN = (2 * ((2 * i) - 1)) * catalanNumberN / (i + 1);
- }
- //MEDIUM SPEED
- // for N = 100000 , runtime: 00:01:52.81
- //BigInteger divident = CalculateFactorial(2 * numberN);
- //BigInteger nFactorial = CalculateFactorial(numberN);
- //BigInteger nFactorialPlus1 = nFactorial * (numberN + 1);
- //BigInteger divider = nFactorial * nFactorialPlus1;
- //BigInteger catalanNumberN = divident / divider;
- // SLOWEST METHOD
- //for N = 100000 , runtime: 00:02:09.23
- //BigInteger catalanNumberN = CalculateFactorial(2 * numberN) / (CalculateFactorial(numberN + 1) * CalculateFactorial(numberN));
- stopWatch.Stop();
- Console.WriteLine("The {0} Catalan number is {1}" + Environment.NewLine, numberN, catalanNumberN);
- TimeSpan ts = stopWatch.Elapsed;
- string elapsedTime = String.Format("{0:00}:{1:00}:{2:00}.{3:00}", ts.Hours, ts.Minutes, ts.Seconds, ts.Milliseconds / 10);
- Console.WriteLine("runtime: " + elapsedTime + Environment.NewLine);
- }
- }
- static BigInteger InputData()
- {
- BigInteger numberN;
- string invalidInput = "Please enter a valid number greater than or equal to 0!" + Environment.NewLine;
- Console.WriteLine("Enter a value for N: ");
- while (!(BigInteger.TryParse(Console.ReadLine(), out numberN) && numberN >= 0))
- {
- Console.WriteLine(invalidInput);
- Console.WriteLine("Enter a value for N: ");
- }
- return numberN;
- }
- static BigInteger CalculateFactorial(BigInteger numberN)
- {
- BigInteger factorial = 1;
- for (BigInteger i = 1; i <= numberN; i++)
- {
- factorial = factorial * i;
- }
- return factorial;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment