Loading...

Във форума е въведено ограничение, което позволява на потребителите единствено да разглеждат публикуваните въпроси.

James242 avatar James242 0 Точки

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

Тагове:
0
Programming Basics
AntyfrizZz avatar AntyfrizZz 238 Точки
Best Answer

Hello James,

 

I will try to explain it to you.

N = 8, K = 5

N! = 8 * 7 * 6 * 5 * 4 * 3 * 2 * 1

K! = 5 * 4 * 3 * 2 * 1

=> N! / K! = (8 * 7 * 6 * K!) / K! = 8 * 7 * 6

As you can see, there is no need to calculate K!, because we will divide N! to K!. All we need is to calculate 8 * 7 * 6, which is exactly what the given for cycle do.

 

Best Regards!

0
James242 avatar James242 0 Точки

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.

 

0
AntyfrizZz avatar AntyfrizZz 238 Точки

Yes, and including this numbers in the calculations is unnecessarily.

0
Slavi007 avatar Slavi007 0 Точки

Hello, James.

I will try to show the mathematic logic on the problem you have.

If we examine your code which is absolutely correct we can see that if k is 2 and n is 4 the code methodically calculates n!/k! 

For example (using your code): we type n= 4 and k=2, then the code calculates n! = 24 and k! = 2 and then return n!/k! = 12 and that is correct.

The second solution is also correct and it is also quite faster to be compiled. 

For example (using the second solution) we type n=4 and k=2 then the for loop starts and here comes the magic. i starts from k+1 which is 3 in this example and i is added to result = result*i; Then i = 4 and it is again added to result which is now 3 and now becomes 3*4 =12; 

You can try with other numbers but the result will be always n!/k!

Hope to help you with this.

Regards, Slavi

 

0
James242 avatar James242 0 Точки

Love it!  Thanks so much for explaining this to me in English!  Nice people in this forum.

0
AexeDivan avatar AexeDivan 1 Точки

Chapter six and division for further aspect I counted for the joint operations. Elevation of the shades of the chapter and https://www.edugeeksclub.com/coursework/ is sided for the students. The new shape of the chapter is put to light for the elevations for the right use of the offers.

0
Можем ли да използваме бисквитки?
Ние използваме бисквитки и подобни технологии, за да предоставим нашите услуги. Можете да се съгласите с всички или част от тях.
Назад
Функционални
Използваме бисквитки и подобни технологии, за да предоставим нашите услуги. Използваме „сесийни“ бисквитки, за да Ви идентифицираме временно. Те се пазят само по време на активната употреба на услугите ни. След излизане от приложението, затваряне на браузъра или мобилното устройство, данните се трият. Използваме бисквитки, за да предоставим опцията „Запомни Ме“, която Ви позволява да използвате нашите услуги без да предоставяте потребителско име и парола. Допълнително е възможно да използваме бисквитки за да съхраняваме различни малки настройки, като избор на езика, позиции на менюта и персонализирано съдържание. Използваме бисквитки и за измерване на маркетинговите ни усилия.
Рекламни
Използваме бисквитки, за да измерваме маркетинг ефективността ни, броене на посещения, както и за проследяването дали дадено електронно писмо е било отворено.