C# Book chapter 6 exercise 6 - Dividing by 2 factorials
Hello! I do not speak Bulgarian, but I have finished reading the Fundamentals of Computer Programming with C# book, am going back over some of the exercises I did not initally complete, and am hoping this forum might be useful to me even though I don't speak Bulgarian. I know a lot of you must speak English since much of the course material is in English. I just noticed the language toggle at the bottom of the website's page.
Chapter 6 exercise 6 asks us to "write a program that calculates N!/K! for given N and K (1<K<N).
I wrote a solution to this problem with a calculateFactorial function that is used to calculate N! and then K!, after which those values are divided.
static void Main(string[] args)
{
Console.WriteLine("Enter the first digit to muliply");
BigInteger n = BigInteger.Parse(Console.ReadLine());
Console.WriteLine("Enter the second digit to muliply");
BigInteger k = BigInteger.Parse(Console.ReadLine());
if (1 > k || k > n)
{
Console.WriteLine("second number must be larger than 1 and smaller than first number.");
}
else
{
BigInteger nFactorial = calculateFactorial(n);
BigInteger kFactorial = calculateFactorial(k);
Console.WriteLine("n! = " + nFactorial);
Console.WriteLine("k! = " + kFactorial);
BigInteger output = nFactorial / kFactorial;
Console.WriteLine("{0} / {1} = {2}", nFactorial, kFactorial, output);
}
Console.ReadLine();
}
static BigInteger calculateFactorial(BigInteger x)
{
BigInteger factorial = 1;
do
{
factorial *= x;
x--;
}
while (x > 0);
return factorial;
}
}
However, I'm looking at the word .doc with the solutions and this provided solution is more elegant since it only caluclates k+1 * each n and removes the division step.
for (int i = k+1; i <= n; i++)
{
result *= i;
}
I don't quite understand the mathematical logic on why doing the above caluclation is the same as N!/K!
Any insight on this topic would be very much appreciated!
James
Love it! Thanks so much for explaining this to me in English! Nice people in this forum.