2015-07-20 91 views
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(); 
} 
+2

http://rosettacode.org/wiki/Catalan_numbers#C.23 –

+4

为factorial等编写一些辅助方法可能是一个很好的练习。 –

+0

非常感谢大家。 – haby

回答

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 )。除此之外,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 与该计算,一个long可以得到至少到C ,这是我可以打扰检查。

+1

所以使用'long'而不是'int'。它会在某个时候溢出,但是数量会更大。 –

+1

@MatthewWatson你可以使用[BigInteger](https://msdn.microsoft.com/en-us/library/system.numerics.biginteger(v = vs.110).aspx)任意大的内容,但性能会受到影响对于可以通过“长” –

+0

覆盖的情况,我已经尝试过“小数”和“长”。我现在使用'double',它可以工作直到n = 85,然后它给出无穷大。非常感谢你的帮助。 – haby