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)
回答(1 个)
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
2019-4-23
KSSV
2019-4-23
Is it the sum of only even or all numbers?
YING ZE SOON
2019-4-23
类别
在 帮助中心 和 File Exchange 中查找有关 Logical 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!