c# - Calculating Catalan Number -
i using code calculate catalan number. gives me right value until n=6 , gives me wrong values. checked manually using calculator. ex: when n=5 catalan number 42 right when n=7 , gives me 6 wrong answer should 429. cant figure out whats wrong. can 1 me please?
static void main(string[] args) { int i, n, fact, fact1, fact2, catalann; console.writeline("enter number (n>=0)"); n = convert.toint32(console.readline()); fact = n; (i = n - 1; > 0; i--) { fact = fact * i; } console.writeline("" + fact); console.readline(); fact1 = 2*n; (i = 2*n - 1; > 0; i--) { fact1 = fact1 * i; } console.writeline("" + fact1); console.readline(); fact2 = n+1; (i = (n+1)-1; > 0; i--) { fact2 = fact2 * i; } console.writeline("" + fact2); console.readline(); catalann = fact1 / (fact2 * fact); console.writeline("catalan number of given number : " + catalann); console.readline(); }
if change second loop to:
for (i = 2*n - 1; > 0; i--) { int old = fact1; fact1 = fact1 * i; console.writeline("" + old + " " + fact1); } then you'll see you're suffering overflow (slightly reformatted line values):
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 this due factorial-type terms in calculations. changing type long give more breathing space (allowing c10). beyond that, decimal can go little further may have end using arbitrary-precision math library (like system.numerics.biginteger) higher numbers.
you may want use less onerous calculation minimises interim terms little:
n = convert.toint32(console.readline()); catalann = 1; term = 0; while (n-- > 1) { term++; catalann = catalann * (4 * term + 2) / (term + 2); } this give more breathing space, regardless of data type use. our lowly int can c16 calculation, long can @ least c25, far bothered check.
Comments
Post a Comment