#Project Euler/Python/Problem16.py #Matthew Ellison # Created: 02-03-19 #Modified: 07-24-21 #What is the sum of the digits of the number 2^1000? #Unless otherwise listed, all of my non-standard imports can be gotten from my pyClasses repository at https://bitbucket.org/Mattrixwv/pyClasses """ 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 . """ from Problems.Problem import Problem class Problem16(Problem): #Variables __numToPower = 2 #The number that is going to be raised to a power __power = 1000 #The power that the number is going to be raised to #Functions #Constructor def __init__(self) -> None: super().__init__("What is the sum of the digits of the number 2^1000?") self.num = 0 self.sumOfElements = 0 #Operational functions #Solve the problem def solve(self) -> None: #If the problem has already been solved do nothing and end the function if(self.solved): return #Start the timer self.timer.start() #Get the number self.num = self.__numToPower ** self.__power #Change the number to a string stringOfNum = str(self.num) #Step through the string one element at a time for cnt in range(0, len(stringOfNum)): #Change the character to an int and add it to the sum self.sumOfElements += int(stringOfNum[cnt]) #Stop the timer self.timer.stop() #Throw a flag to show the problem is solved self.solved = True #Reset the problem so it can be run again def reset(self) -> None: super().reset() self.num = 0 self.sumOfElements = 0 #Gets #Returns the result of solving the problem def getResult(self) -> str: #If the problem hasn't been solved throw an exception self.solvedCheck("result") return f"{self.__numToPower}^{self.__power} = {self.num}\n" \ f"The sum of the elements is {self.sumOfElements}" #Returns the number that was calculated def getNumber(self) -> int: self.solvedCheck("number") return self.num #Return the sum of digits of the number def getSum(self) -> int: self.solvedCheck("sum") return self.sumOfElements """Results: 2^1000 = 10715086071862673209484250490600018105614048117055336074437503883703510511249361224931983788156958581275946729175531468251871452856923140435984577574698574803934567774824230985421074605062371141877954182153046474983581941267398767559165543946077062914571196477686542167660429831652624386837205668069376 The sum of the elements is 1366 It took an average of 57.271 microseconds to run this problem through 100 iterations """