From c80941d3fb543f6d44e6131b7b8423f099a2cf2c Mon Sep 17 00:00:00 2001 From: Mattrixwv Date: Tue, 1 Jun 2021 19:56:18 -0400 Subject: [PATCH] Added solution to problem 34 --- Problem34.m | 68 +++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 68 insertions(+) create mode 100644 Problem34.m diff --git a/Problem34.m b/Problem34.m new file mode 100644 index 0000000..ab02822 --- /dev/null +++ b/Problem34.m @@ -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 . +%} + +%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 +%}