Files
ProjectEulerOctave/Problem30.m
2021-05-28 16:13:56 -04:00

80 lines
2.8 KiB
Matlab

function [] = Problem30()
%ProjectEuler/Octave/Problem30.m
%Matthew Ellison
% Created: 10-28-19
%Modified: 10-28-19
%Find the sum of all the numbers that can be written as the sum of the fifth powers of their digits.
%{
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/>.
%}
%Setup the variables
TOP_NUM = 1000000; %This is the largest number that will be check
BOTTOM_NUM = 2; %Starts with 2 because 0 and 1 don't count
POWER_RAISED = 5; %This is the power that the digits are raised to
sumOfFifthNumbers = []; %This is an array of the numbers that are the sum of the fifth power of their digits
sumOfArray = 0; %This is the sum of the sumOfFifthNumbers array
%Start the timer
startTime = clock();
%Start with the lowest number and increment until you reach the largest number
for currentNum = BOTTOM_NUM : TOP_NUM
printf("%d\n", currentNum)
%Get the digits of the number
digits = getDigits(currentNum);
%Get the sum of the powers
sumOfPowers = 0;
for cnt = 1 : size(digits)(2)
sumOfPowers += digits(cnt)^POWER_RAISED;
end
%Check if the sum of the powers is the same as the number
%If it is add it to the list, otherwise continue to the next number
if(sumOfPowers == currentNum)
sumOfFifthNumbers(end + 1) = currentNum;
end
end
sumOfArray = sum(sumOfFifthNumbers);
%Stop the timer
endTime = clock();
%Print the results
printf("The sum of all the numbers that can be written as the sum of the fifth powers of their digits is %d\n", sumOfArray)
printf("It took %f seconds to run this algorithm\n", etime(endTime, startTime))
end
%Returns an array with the individual digits of the number passed to it
function [listOfDigits] = getDigits(num)
listOfDigits = []; %This array holds the individual digits of num
%The easiest way to get the individual digits of a number is by converting it to a string
digits = num2str(num);
%Start with the first digit, convert it to an integer, store it in the table, and move to the next digit
for cnt = 1 : size(digits)(2)
listOfDigits(end + 1) = str2num(substr(digits, cnt, 1));
end
end
%{
Results:
The sum of all the numbers that can be written as the sum of the fifth powers of their digits is 443839
It took 1849.877525 seconds to run this algorithm
%}