Out of memory Problem [Problem 2 , Project Euler (Sum of even Fibonacci numbers)]
Show older comments
%When i tried x=597455000 it straightly said, out of memory problem.
%How can i fix this problem ?
%Give me some advices

function y=shadowofeuler(x)
m(1)=1;
m(2)=1;
i=3;
while(x>=i)
m(i)= m(i-1)+m(i-2);
i=i+1;
end
n=m(3:3:end);
y=sum(n(find(n<x)));
end
Accepted Answer
More Answers (2)
James Tursa
on 10 May 2020
0 votes
Don't store all of the numbers as you go and then add them up at the end. Only keep a few numbers in memory at one time and do the summing as part of your looping.
2 Comments
Syed Shahed
on 10 May 2020
James Tursa
on 10 May 2020
Edited: James Tursa
on 10 May 2020
E.g. the basic structure of the loop would be
m1 = 1;
m2 = 1;
while( some condition of your choosing )
m3 = m1 + m2; % the new number
% do something with the new number m3
% e.g., maybe you add m3 into your total sum if it meets a condition
m1 = m2; % shift m2 into m1
m2 = m3; % shift m3 into m2
end
The loop can go on for quite some time (basically until double precision limit is reached), and there are only three terms in memory at once.
Osahon Usuanlele
on 15 Dec 2020
def fibs(num):
arr = [1,1]
count = 1
while count < num - 1:
arr.append(arr[len(arr)-1] + arr[len(arr)-2])
count+=1
arr.pop(0)
print(arr)
fibs(1000)
Categories
Find more on Loops and Conditional Statements in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!