%ProjectEuler/Octave/Problem20.m %Matthew Ellison % Created: 03-14-19 %Modified: 03-28-19 %What is the sum of the digits of 100!? %This project uses the symbolic library. Make sure that you install the symbolic library as well as sympy before running this script %The way to do this is run this command in octave: pkg install -forge symbolic %This library requires sympy as well. This is easily installed with pip: pip install sympy %{ 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 . %} pkg load symbolic; digits(500) %Keep track of enough digits to do this calculation correctly %The number that will hold 100! syms num; syms x; %A helper that will allow us to do easy math with the symbolics num = 1 * x; num = subs(num, x, 1); %Setup the rest of our variables sumOfNums = 0; %Holds the sum of the digits of num TOP_NUM = 100; %The number that we are trying to factorial %Start the timer startTime = clock(); %Run through every number from 1 to 100 and multiply it by the current number for cnt = 1 : TOP_NUM num = num * x; num = subs(num, x, cnt); end %Get a string of the numebr because it is easier to pull appart the individual characters for the sum numString = char(num); %Run through every character in the string, convert it back to an integer and add it to the running sum for cnt = 1 : size(numString)(2) sumOfNums += str2num(numString(cnt)); end %Stop the timer endTime = clock(); %Print the results printf("100! = %s\n", numString) printf("The sum of the digits is: %d\n", sumOfNums) printf("It took %f seconds to run this algorithm\n", etime(endTime, startTime)) %{ 100! = 93326215443944152681699238856266700490715968264381621468592963895217599993229915608941463976156518286253697920827223758251185210916864000000000000000000000000 The sum of the digits is: 648 It took 6.356117 seconds to run this algorithm %}