mirror of
https://bitbucket.org/Mattrixwv/projecteuleroctave.git
synced 2025-12-06 09:33:58 -05:00
73 lines
1.9 KiB
Matlab
73 lines
1.9 KiB
Matlab
%ProjectEuler/Octave/Problem9.m
|
|
%Matthew Ellison
|
|
% Created:
|
|
%Modified: 03-28-19
|
|
%There exists exactly one Pythagorean triplet for which a + b + c = 1000. Find the product abc.
|
|
%{
|
|
Copyright (C) 2019 Matthew Ellison
|
|
|
|
This program is free software: you can redistribute it and/or modify
|
|
it under the terms of the GNU Lesser General Public License as published by
|
|
the Free Software Foundation, either version 3 of the License, or
|
|
(at your option) any later version.
|
|
|
|
This program is distributed in the hope that it will be useful,
|
|
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
|
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
|
GNU Lesser General Public License for more details.
|
|
|
|
You should have received a copy of the GNU Lesser General Public License
|
|
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
|
%}
|
|
|
|
|
|
%Create the variable
|
|
a = 1;
|
|
b = 0;
|
|
c = 0;
|
|
found = false;
|
|
|
|
%Start the timer
|
|
startTime = clock();
|
|
|
|
%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)
|
|
++b;
|
|
c = sqrt(a^2 + b^2);
|
|
end
|
|
%If you haven't found the numbers yet, increment a and try again
|
|
if((a + b + c) == 1000)
|
|
found = true;
|
|
else
|
|
++a;
|
|
end
|
|
end
|
|
|
|
%Stop the timer
|
|
endTime = clock();
|
|
|
|
%print the results
|
|
printf("The Pythagorean triplet where a + b + c = 1000 is %d %d %d\n", a, b, c)
|
|
printf("The product of those numbers is %d\n", a * b * c)
|
|
printf("It took %f seconds to run this algorithm\n", etime(endTime, startTime))
|
|
|
|
%Cleanup the variables
|
|
clear a;
|
|
clear b;
|
|
clear c;
|
|
clear found;
|
|
clear startTime;
|
|
clear endTime;
|
|
clear ans;
|
|
|
|
%{
|
|
Results:
|
|
The Pythagorean triplet where a + b + c = 1000 is 200 375 425
|
|
The product of those numbers is 31875000
|
|
It took 0.573143 seconds to run this algorithm
|
|
%}
|