我正在使用此代码计算加泰罗尼亚数字。它给了我正确的值,直到n = 6,然后它给了我错误的值。我用计算器手动检查了。对于Ex:当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();
}
答案 0 :(得分:5)
如果您将第二个循环更改为:
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 ,long
也可以得到至少C 25 ,这是至于我可能会被打扰检查。
答案 1 :(得分: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);
}