View Single Post
Old 10-23-2011, 02:53 AM   #25
foilman8805
smoke wheat hail satin
FFR Simfile AuthorFFR Veteran
 
foilman8805's Avatar
 
Join Date: Sep 2006
Location: LA baby
Age: 36
Posts: 5,704
Default Re: THE project euler thread

Thanks OP for giving me something to do with my brain while I'm in between jobs. This is awesome. I'll be programming in MATLAB/Octave. I just did the first two problems as a bit of a warm up and it was a lot of fun.

Problem 1
Code:
%% Euler Project - Problem 1 

% Find the sum of all multiples of 3 or 5 below 1000. 

sum = 0;

for i=3:999
    if rem(i,3) == 0 || rem(i,5) == 0
        sum = sum + i;
    end
end

sum


Problem 2
Had to first write a function to calculate the numbers in the Fibonacci sequence given any input:
Code:
function fib = fibonacci(x)

if x == 0
    fib = 0;
elseif x == 1
    fib = 1;
else
    fib = fibonacci(x-1) + fibonacci(x-2);
end

I then implemented that function in the script file below to find the solution:
Code:
%% Euler Project - Problem 2

% By considering the terms in the Fibonacci sequence whose values do not
% exceed four million, find the sum of the even-valued terms.

% First need to find at what term the Fibonacci sequence goes over 
% 4 million. I created a supplimentary function file called fibonacci.m 
% that calculates the values of the Fibonacci sequence given an input.
% i.e. fibonacci(10) will output 89. 

i = 0;
fib = 0;

while fib <= 4000000
    i = i + 1;
    fib(i) = fibonacci(i);
end

% The loop above identifies that there are 33 values in the Fibonacci sequence
% that don't exceed 4,000,000. Now we will add up each even term. 

for j = 1:33
    if rem(fib(j),2) == 0
        sumfib(j,1) = fib(j);
    else
        sumfib(j,1) = 0;
    end
end
    
answer = sum(sumfib)

Last edited by foilman8805; 10-23-2011 at 03:14 AM..
foilman8805 is offline   Reply With Quote