3

我正在使用此代码来计算加泰罗尼亚语数。它给了我正确的价值,直到 n=6 ,然后它给了我错误的价值。我使用计算器手动检查。例如:当 n=5 加泰罗尼亚数字是 42 时,这是正确的,但当 n=7 时,它给了我 6,这是完全错误的,因为答案应该是 429。我只是想不出什么是错的。有人能帮助我吗?

static void Main(string[] args)
{
    int i, n, fact, fact1, fact2, CatalanN;
    Console.WriteLine("Enter a Number (n>=0)");

    n = Convert.ToInt32(Console.ReadLine());
    fact = n;

    for (i = n - 1; i > 0; i--)
    {
        fact = fact * i;
    }
    Console.WriteLine("" + fact);
    Console.ReadLine();

    fact1 = 2*n;

    for (i = 2*n - 1; i > 0; i--)
    {
        fact1 = fact1 * i;
    }
    Console.WriteLine("" + fact1);
    Console.ReadLine();

    fact2 = n+1;

    for (i = (n+1)-1; i > 0; i--)
    {
        fact2 = fact2 * i;
    }
    Console.WriteLine("" + fact2);
    Console.ReadLine();

    CatalanN = fact1 / (fact2 * fact);
    Console.WriteLine("Catalan Number of the given number is : " + CatalanN);
    Console.ReadLine();
}
4

2 回答 2

6

如果您将第二个循环更改为:

for (i = 2*n - 1; i > 0; i--)
{
    int old = fact1;
    fact1 = fact1 * i;
    Console.WriteLine("" + old + " " + fact1);
}

然后你会看到你正在遭受溢出(稍微重新格式化以排列值):

        14        182
       182       2184
      2184      24024
     24024     240240
    240240    2162160
   2162160   17297280
  17297280  121080960
 121080960  726485760
 726485760 -662538496 <- overflow occurs here.
-662538496 1644813312
1644813312  639472640
 639472640 1278945280
1278945280 1278945280

这是由于计算中的阶乘类型项。将类型更改为long将为您提供更多的喘息空间(允许您执行 C 10)。除此之外,decimal可以走得更远,但您可能最终不得不使用任意精度的数学库(如System.Numerics.BigInteger)来获取更高的数字。

您可能希望使用稍微不那么繁琐的计算,以使临时条款最小化一点:

n = Convert.ToInt32(Console.ReadLine());
CatalanN = 1;
Term = 0;
while (n-- > 1) {
    Term++;
    CatalanN = CatalanN * (4 * Term + 2) / (Term + 2);
}

无论您使用哪种数据类型,这都会提供更多的喘息空间。即使是我们的低级int人员也可以通过该计算达到 C 16, along至少可以达到 C 25,这是我可能懒得去检查的。

于 2015-07-20T07:47:24.347 回答
0

下面的代码如何使用长数据类型

public static long BracketCombinations(long num){
    // Using Catalan Formula
    if(num <= 0)
        return 0;
    long Combinations = (Factorial(2 * num)) / ((Factorial(num + 1)) * (Factorial(num)));
    return Combinations;
}

public static long Factorial(long num){
    if(num == 1)
        return 1;
    return num * Factorial(num-1);
}
于 2021-08-02T12:17:11.137 回答