2015-07-20 93 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