Advertisement
dimipan80

6.7Loops_CalculateFactorialsDivisionAdvanced

Mar 24th, 2014
1,000
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 2.08 KB | None | 0 0
  1. using System;
  2. using System.Numerics;
  3.  
  4. class FactorialsDivisionAdvanced
  5. {
  6.     static void Main ()
  7.     {
  8.         checked
  9.         {
  10.             Console.Write("Please, enter a whole number, bigger from 1 for K = ");
  11.             string numberStr = Console.ReadLine();
  12.             int numK = int.Parse(numberStr);
  13.             Console.Write("Enter other whole number, bigger from K for N = ");
  14.             numberStr = Console.ReadLine();
  15.             int numN = int.Parse(numberStr);
  16.             if (numK < 2 || numN < 3 || numN <= numK || numK >= 100 || numN >= 100)
  17.             {
  18.                 Console.WriteLine("Error - Invalid Input !!!");
  19.             }
  20.             else
  21.             /* The factorial function (symbol: !) means to multiply a series of descending
  22.              * natural numbers. That means N! = N * (N - 1) * (N - 2) * ... * 1 also and
  23.              * K! = K * (K - 1) * (K - 2) * ... * 1.
  24.              * If N > K, K! is Subset of N!, wich means:
  25.              * N! = N * (N - 1) * (N - 2) * ... * (K + 1) * K!
  26.              * To optimize time and performance of this application, we will reduce initial
  27.              * formula from task conditions  RESULT = N! / (K! * (N - K)!)  to next:            
  28.              * 1) = First loop multiplay numbers from N to K + 1;
  29.              * 2) = Second loop calculate Factorial of (N - K)!;
  30.              * RESULT = 1) / 2) . Example: N=7 and K=4, RESULT = 35.   */
  31.  
  32.             {
  33.                 BigInteger factorialNtoK = 1;
  34.                 for (int i = numN; i > numK; i--)
  35.                 {
  36.                     factorialNtoK *= i;
  37.                 }
  38.  
  39.                 BigInteger dividerFactorial = 1;
  40.                 for (int j = 2; j <= (numN - numK); j++)
  41.                 {
  42.                     dividerFactorial *= j;
  43.                 }
  44.  
  45.                 BigInteger resultDivision = factorialNtoK / dividerFactorial;
  46.                 Console.WriteLine("The result from that factorials division is:");
  47.                 Console.WriteLine("RESULT = {0} !", resultDivision);
  48.             }
  49.             Console.ReadLine();
  50.         }
  51.     }
  52. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement