I have a task to find number of expressions containing n parentheses which are correctly matched. So, I decided to use Catalan number. Here is a python code.
from decimal import Decimal
n = int(input())
res = Decimal(1)
k = n//2
for i in range(1, k+1):
res = Decimal(res*(n-k+i)/i)
res = int(res)
print(int(res//(k+1)))
After testing it in testing system, I have only 2 correct answers of 100. When: n = 2 (answer: 1) ans n = 4 (answer: 2). I can't look at other testing examples. Can you, please, help me? Where am I wrong?
You are probably trying to use Decimal numbers because your know that floating point arithmetic is broken. Unfortunately Decimal arithmetic is broken too and for the same underlying reason: rational numbers can only be exactly represented if the denominator of the reduced fraction only contains factors dividing
10in that numeration system.In base 2 (common floating point) only 1/2**n fractions can be represented, so
0.2(1/5) can only be represented as an approximation. But in base 10,0.1can indeed be represented but 1/3 is the infinite 0.33333... that will be an approximation in a finite computer.As you use rational numbers that by construction will finally give integer values, you have two possible paths:
fractions.Fraction: a Fraction keeps separatedly its numerator and denominator parts. So all rational arithmetics give an exact representation (as a Fraction but neither as a floating point or Decimal)TL/DR: just replace Decimal with Fraction if you want exact rational arithmetics
But you formule looks weird. According to Wikipedia, it should be
Prod(n-k/k) for 2<=k<=n:I can confirm that this formula gives the first 10 Catalan numbers.