How do i code this question?

The Catalan number series is given by C(n) = (2n)!/((n+1)!n!) where n! represents the factorial of n and n is an integer starting at 1. Therefore ,the first10 Catalan numbers for n=1:10 are given by:[1,2,5,14,42,132,429,1430,4862,16796]. The sum of all the even Catalan numbers in this range is 23278(i.e.2+14+42+132+1430+4862+16796). Determine the sum of all even Catalan numbers in the range if n=10:20.
i managed to code this but Matlab's decimal place has round it off making some number become odd numbers .How do i deal with this problem?
c=zeros;
d=zeros;
for n=10:20
c(n) = factorial(2*n)/((factorial(n+1))*factorial(n));
format long g
e = c(n);
if mod(e,2) == 0 || mod(e,2) <=1
d(n) = e(true);
else
false;
end
end
y = sum(d)

Answers (1)

KSSV
KSSV on 23 Apr 2019
Edited: KSSV on 23 Apr 2019
Loop is not required.
format long g
n=(10:20)' ;
c = factorial(2*n)./((factorial(n+1)).*factorial(n));
idx = mod(n,2)==0 ; % get even locations
sum(c(idx))

3 Comments

Thanks for the guidance but im afraid that the ans for the range n=10:20 is 8977700000
Is it the sum of only even or all numbers?
only even numbers, when i use the calculator to calculate the range it is all even but because matlab calculate it to be something like 29.999999999 which matlab count it as odd number where the calculator only shows 30 which is even.

Sign in to comment.

Asked:

on 23 Apr 2019

Commented:

on 23 Apr 2019

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!