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)

답변 (1개)

KSSV
KSSV 2019년 4월 23일
편집: KSSV 2019년 4월 23일

0 개 추천

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

YING ZE SOON
YING ZE SOON 2019년 4월 23일
Thanks for the guidance but im afraid that the ans for the range n=10:20 is 8977700000
KSSV
KSSV 2019년 4월 23일
Is it the sum of only even or all numbers?
YING ZE SOON
YING ZE SOON 2019년 4월 23일
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.

댓글을 달려면 로그인하십시오.

카테고리

도움말 센터File Exchange에서 Logical에 대해 자세히 알아보기

질문:

2019년 4월 23일

댓글:

2019년 4월 23일

Community Treasure Hunt

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

Start Hunting!

Translated by