简体   繁体   中英

Combination by using factorial function method

I cannot combinate 20 and 17, the program says that the result is 1. Why?? I'm sure my code is right but i just cannot combinate big numbers.

using System;
namespace question
{
    class beat_That
    {
        static int Factorial(int m)
        {
            int result = 1;
            for (int i = 1; i <= m; i++)
            {
                result *= i;
            }
            return result;
        }
        static void Main(string[] args)
        {
            Console.WriteLine("enter number of objects in the set: ");
            int n = Convert.ToInt32(Console.ReadLine());

            Console.WriteLine("enter number to be chosen: ");
            int k = Convert.ToInt32(Console.ReadLine());

            int combination = Factorial(n) / (Factorial(n - k) * Factorial(k));
            Console.WriteLine("C(" + n + ", " + k + ") = " + combination);

            Console.ReadKey();

        }
    }
}

I'm guessing this is a homework assignment? Here are some tips that will hopefully get you going in the right direction:

(1) Typically, .NET classes are Pascal Case , so for example: comb should be Comb . Also, it's better to assign descriptive class names instead of short abbreviations. For clarity I'm going to assume you at least rename comb to Comb so it isn't confused with a variable name, but another option might be Calculator for example.

(2) Check your syntax and any compiler errors. For example, the compiler should be complaining about this line of code: Console.WriteLine("the combination of {0} and {1} is {2}. "),a1,b1,;

(3) Your methods Factorial and Combination are static methods (as opposed to instance methods). This changes how you call these methods. Static methods are called without an instance, for example: Comb.Combination(..)

(4) Make sure you test various inputs! Your implementation of Combination is not quite correct, but I'll leave that as an exercise to figure out why.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM