How could I neaten this code up.
이전 댓글 표시
Hi
Currently working through some of Project Eulers problems as mentioned in the forum discussion 'Best way(s) to master MATLAB'. I have created this code, it works but there is something about it I find messy. For a start I don't like all the declared variables.
function eusol2 = euler2(euin)
% for No's in fibonacci sequence < 4mil, sum all even No terms.
x = [1 2];
y = 1;
xout = 2;
fibMax = 0;
while fibMax < euin
fibMax = x(1) + x(2);
if fibMax < euin
if mod(fibMax, 2) == 0;
xout = xout + fibMax;
else
end
else
end
x(y) = fibMax;
y = 3 - y;
eusol2 = xout;
end
Any suggestions or remarks
AD
댓글 수: 3
bym
2011년 10월 24일
your first if-else-end block is unnecessary, because fibMax<euin is a condition of entering the while loop
Jan
2011년 10월 25일
@procsm: But the value of fibMax has been increased since the WHILE.
Jan
2011년 10월 26일
You started the sequence with [1,2] accidently instead of [1,1]. Using xout=2 instead of 0 compensates this such that the correct answer is calculated.
A very nice example for a "stealth bug": No effect for standard usage, generalising the function for any Fibonacci sequence [a,b] fails.
채택된 답변
추가 답변 (3개)
bym
2011년 10월 24일
0 개 추천
Have a look at Binet's formula and look for a pattern in the distribution of even Fibonnaci numbers...I bet a one liner could be written
Daniel Shub
2011년 10월 25일
x = [1 2];
eusol2 = 0;
while sum(x) < euin
if mod(sum(x), 2) == 0;
eusol2 = eusol2 + sum(x);
end
x = [x(2), sum(x)];
% k = sum(x);
end
This will likely be a little slower since it calculates the sum(x) 4 times per loop. If you add another declared variable (k) you can make it so sum(x) is calculated only once. I eliminated y, because it doesn't seem to do anything.
bym
2011년 10월 26일
just to let you know where I was headed:
clc;clear;tic
phi = (1+sqrt(5))/2;
i = 1:11; % 11 even terms < 4e6
fib = (phi.^(i.*3)-(-1/phi).^(i.*3))/sqrt(5);
fprintf('%6.0f\n',sum(fib))
toc
as Jan suspected, it runs slower than yours (about .8 msec vs .07 msec). +1 vote for the question
카테고리
도움말 센터 및 File Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!