Luis F Llano - 11 months ago 61

Python Question

I'm new to python (and programming in general), I was asked in my class to calculate Catalan numbers up to a billion but the program I wrote for it is not working as intended.

`from numpy import division`

C=1

n=0

while C<=10000000000:

print (C)

C=(4*n+2)/(n+2)*C

n=n+1

This is what it prints

1,

1,

2,

4,

8,

24,

72,

216,

648,

1944,

5832,

17496,

52488,

157464,

472392,

1417176,

4251528,

12754584,

38263752,

114791256,

344373768,

1033121304,

3099363912,

9298091736,

As you can see from my fourth iteration onwards, I get the wrong number and I don't understand why.

EDIT:

The mathematical definition I used is not wrong! I know the Wiki has another definition but this one is not wrong.

Co=1, Cn+1 = (4*n+2)/(n+2)*Cn

Answer Source

```
C=(4*n+2)/(n+2)*C
```

This applies the calculation in the wrong order. Because you are using integer arithmetic, `(4*n+2)/(n+2)`

loses information if you have not already factored in `C`

. The correct calculation is:

```
C=C*(4*n+2)/(n+2)
```