View Single Post
Old 10-26-2011, 03:30 AM   #106
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

Took a stab at a few more problems tonight:

Problem 28
MATLAB is a little cheap with respect to creating a spiral function - it already has one built in, so I utilized it to find my solution. Also, most of my codes for Project Euler are scripts, but for some reason I decided to actually make this one a function. No real reason.
Code:
%% Project Euler - Problem 28

% What is the sum of the numbers on the diagonals in a 1001 by 1001 spiral
% formed in the same way?

function diag_sum = eulerproject28(n)
tic
spiral_matrix_a = spiral(n);
spiral_matrix_b = rot90(spiral_matrix_a);

trace_a = zeros(n,1);
trace_b = zeros(n,1);

for i = 1:n
    trace_a(i) = spiral_matrix_a(i,i);
    trace_b(i) = spiral_matrix_b(i,i);
end

trace_array = [trace_a; trace_b];
trace_array = trace_array(:);
trace_array_unique = unique(trace_array);

diag_sum = sum(trace_array_unique);
toc
end


Problem 29
This one turned out to be pretty easy. Just used a nested for loop and then eliminated all of the elements I didn't want in my vectors (i.e. repeating values).
Code:
%% Project Euler - Problem 29

% How many distinct terms are in the sequence generated by ab for 2 <= a <=
% 100 and 2 <= b <= 100?
tic
for a = 2:100
    for b = 2:100
        a_b(a,b) = a^b;
    end
end
a_b_lin = a_b(:);
a_b_unique = unique(a_b_lin);
[c,d] = find(a_b_unique <= 0);
a_b_final = a_b_unique(c+1:end)';
distinct_terms = length(a_b_final)
toc


I also came up with brute force solutions to Problems 71-73, which actually work with small sample sizes, but MATLAB is pretty horrible with big numbers as well as large volumes of numbers, so it takes a crap when I run it and says it doesn't have enough memory. I bought an 8GB flashdrive online today that's ReadyBoost enabled, so hopefully when I get it I can run my programs.

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