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
Thank you! I understand this a lot better after reading your explanation.
The color coding is particularly helpful.
So to me this looks kind of similar to the logic of simplifying fractions.
It seems like you're saying that we don't have to consider 5 because 5 is on the bottom and top of the division bar and 5/5 = 1, so we cancel it out because anything later multiplied by 1 is itself anyway.
Then the same is true for 4, 3, 2, and 1.
Yes, and including this numbers in the calculations is unnecessarily.