Added solution for problem 9

This commit is contained in:
2018-09-26 12:29:12 -04:00
parent 5f5162db01
commit 316835bd60

39
ProjectEuler/Problem9.m Normal file
View File

@@ -0,0 +1,39 @@
%ProjectEuler/Problem9.m
%This is a script to answer Problem 9 for Project Euler
%There exists exactly one Pythagorean triplet for which a + b + c = 1000. Find the product abc.
%Create the variable
a = 1;
b = 0;
c = 0;
found = false;
%Start with the smallest possible a
while((a < 1000) && ~found)
b = a + 1; %b must be > a
c = sqrt(a^2 + b^2); %c^2 = a^2 + b^2
%Loop through all possible b's. When the sum of a, b, c is > 1000. You done have the number. Try the next a
while(((a + b + c) <= 1000) && ~found)
%If the sum == 1000 you found the numbers
if((a + b + c) == 1000)
found = true;
%Otherwise try the next b and recalculate c
else
++b;
c = sqrt(a^2 + b^2);
end
end
%If you haven't found the numbers yet, increment a and try again
if(~found)
++a;
end
end
%print the result
a * b * c
%Cleanup the variables
clear a;
clear b;
clear c;
clear found;