mirror of
https://bitbucket.org/Mattrixwv/projecteuleroctave.git
synced 2025-12-06 17:43:57 -05:00
Added solution to problem 34
This commit is contained in:
68
Problem34.m
Normal file
68
Problem34.m
Normal file
@@ -0,0 +1,68 @@
|
||||
function [] = Problem34()
|
||||
%ProjectEuler/ProjectEulerOctave/Problem34.lua
|
||||
%Matthew Ellison
|
||||
% Createe: 06-01-21
|
||||
%Modified: 06-01-21
|
||||
%Find the sum of all numbers which are equal to the sum of the factorial of their digits
|
||||
%{
|
||||
Copyright (C) 2021 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
|
||||
|
||||
%Start the timer
|
||||
startTime = clock();
|
||||
MAX_NUM = 1499999; %The largest num that can be the sum of its own digits
|
||||
numberFactorials = []; %Holds the pre-computed factorials of the numbers 0-9
|
||||
totalSum = 0; %Holds the sum of all numbers equal to the sum of their digit's factorials
|
||||
|
||||
%Pre-compute the possible factorials from 0! to 9!
|
||||
for cnt = 1 : 9
|
||||
numberFactorials(cnt) = factorial(cnt);
|
||||
end
|
||||
%Run through all possible numbers from 3-MAX_NUM and see if they equal the sum of their digit's factorials
|
||||
for cnt = 3 : MAX_NUM
|
||||
%Split the number into its digits and add each one to the sum
|
||||
numString = num2str(cnt);
|
||||
currentSum = 0;
|
||||
for numCnt = 1 : size(numString)(2)
|
||||
num = str2num(numString(numCnt));
|
||||
if(num != 0)
|
||||
currentSum += numberFactorials(num);
|
||||
else
|
||||
currentSum += 1;
|
||||
end
|
||||
end
|
||||
%If the number is equal to the sum add the sum to the running sum
|
||||
if(currentSum == cnt)
|
||||
totalSum += currentSum;
|
||||
end
|
||||
end
|
||||
|
||||
%Stop the timer
|
||||
endTime = clock();
|
||||
|
||||
%Print the results
|
||||
printf("The sum of all numbers that are the sum of their digit's factorials is %d\n", totalSum);
|
||||
printf("It took %f seconds to run this algorithm\n", etime(endTime, startTime))
|
||||
|
||||
end
|
||||
|
||||
%{
|
||||
Results:
|
||||
The sum of all numbers that are the sum of their digit's factorials is 40730
|
||||
It took 1988.403809 seconds to run this algorithm
|
||||
%}
|
||||
Reference in New Issue
Block a user