Advertisement
dimipan80

6.21Loops_MultiplyAndDivideFactorials

Mar 23rd, 2014
136
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 2.14 KB | None | 0 0
  1. using System;
  2. using System.Numerics;
  3. class MultiplyAndDivideFactorials
  4. {
  5.     static void Main ()
  6.     {
  7.         checked
  8.         {
  9.             Console.Write("Please, enter a whole number, bigger from 1 for N = ");
  10.             string numberStr = Console.ReadLine();
  11.             int numN = int.Parse(numberStr);
  12.             Console.Write("Enter other whole number, bigger from N for K = ");
  13.             numberStr = Console.ReadLine();
  14.             int numK = int.Parse(numberStr);
  15.             if (numK <= 1 || numN >= numK || numN < 1)
  16.             {
  17.                 Console.WriteLine("Error - Invalid Input !!!");
  18.             }
  19.             else
  20.             {
  21.                 /* If looked deeply in factorial function formula, we will understand
  22.                  * why is not necessarily calculate N! and K! separately.
  23.                  * N!=N*(N-1)*(N-2)*...*1 and K!=K*(K-1)*(K-2)*...1;                 *
  24.                  * If K>N, the factorial of (K-N)! is Subset of K!,
  25.                  * that's mean: K!=K*(K-1)*(K-2)*...*(K-N+1)*(K-N)!;
  26.                  * From all of this follows, to calculate Result from (N!*K!)/(K-N)!,
  27.                  * must calculate only multiplication of two expessions:
  28.                  * 1) Factorial of (K-N+1)*(K-N+2)*...*(K-1)*K;
  29.                  * 2) Factorial of N!
  30.                  * Result = 1) * 2)
  31.                  * Example: If N=4, K=7, 1)=840, 2)=24, Result=20160  */
  32.                
  33.                 BigInteger factorialKToKminusNplus1 = 1;                
  34.                 for (int i = numK; i > (numK - numN); i--)
  35.                 {
  36.                     factorialKToKminusNplus1 *= i;
  37.                 }
  38.  
  39.                 BigInteger factorialN = 1;
  40.                 for (int j = 1; j <= numN; j++)
  41.                 {
  42.                     factorialN *= j;
  43.                 }
  44.  
  45.                 BigInteger multiplicationResult = factorialKToKminusNplus1 * factorialN;
  46.                 Console.WriteLine("The Result of Multiplication and Division of these factorials is:");
  47.                 Console.WriteLine("RESULT = {0} !", multiplicationResult);
  48.             }
  49.             Console.ReadLine();
  50.         }
  51.     }
  52. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement