Updated to use new library layout

This commit is contained in:
2021-07-24 16:13:05 -04:00
parent d18b3fa9f6
commit 84555edd31
39 changed files with 515 additions and 709 deletions

View File

@@ -1,10 +1,10 @@
#ProjectEuler/ProjectEulerPython/Problems/Problem.py #ProjectEuler/ProjectEulerPython/Problems/Problem.py
#Matthew Ellison #Matthew Ellison
# Created: 07-11-20 # Created: 07-11-20
#Modified: 07-11-20 #Modified: 07-23-21
#This is a base class for problems to use as a template #This is a base class for problems to use as a template
""" """
Copyright (C) 2020 Matthew Ellison Copyright (C) 2021 Matthew Ellison
This program is free software: you can redistribute it and/or modify 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 it under the terms of the GNU Lesser General Public License as published by
@@ -28,9 +28,13 @@ from Unsolved import Unsolved
class Problem(metaclass=abc.ABCMeta): class Problem(metaclass=abc.ABCMeta):
#Functions #Functions
#Make sure the problem has been solved and throw an exception if not
def solvedCheck(self, str: str) -> None:
if(not self.solved):
raise Unsolved("You must solve the problem before you can see the " + str)
#Constructor #Constructor
@abc.abstractmethod @abc.abstractmethod
def __init__(self, description: str): def __init__(self, description: str) -> None:
#Instance variables #Instance variables
self.timer = Stopwatch() self.timer = Stopwatch()
self.description = description self.description = description
@@ -39,27 +43,24 @@ class Problem(metaclass=abc.ABCMeta):
#Returns the description of the problem #Returns the description of the problem
def getDescription(self) -> str: def getDescription(self) -> str:
return self.description return self.description
#Returns the time taken to run the problem as a string
def getTime(self) -> str:
self.solvedCheck("time it took to run the algorithm")
return self.timer.getString()
#Returns the timer as a stopwatch
def getTimer(self) -> Stopwatch:
self.solvedCheck("timer")
return self.timer
#Reset the problem so it can be run again
def reset(self) -> None:
self.timer.reset()
self.solved = False
self.result = ""
#Solve the problem
@abc.abstractmethod
def solve(self) -> None:
pass
#Returns the result of solving the problem #Returns the result of solving the problem
@abc.abstractmethod @abc.abstractmethod
def getResult(self) -> str: def getResult(self) -> str:
pass pass
#Returns the time taken to run the problem as a string
def getTime(self) -> str:
#If the problem hasn't been solved throw an exception
if(not self.solved):
raise Unsolved("You must solve the problem before you can see the time")
return self.timer.getString()
#Returns the timer as a stopwatch
def getTimer(self) -> Stopwatch:
#If the problem hasn't been solved throw an exception
if(not self.solved):
raise Unsolved("You must solve the problem before you can see the timer")
return self.timer
#Solve the problem
@abc.abstractmethod
def solve(self):
pass
def reset(self):
self.timer.reset()
self.solved = False
self.result = ""

View File

@@ -1,11 +1,11 @@
#ProjectEuler/Python/Problem1.py #ProjectEuler/Python/Problem1.py
#Matthew Ellison #Matthew Ellison
# Created: 01-26-19 # Created: 01-26-19
#Modified: 10-30-20 #Modified: 07-23-21
#What is the sum of all the multiples of 3 or 5 that are less than 1000 #What is the sum of all the multiples of 3 or 5 that are less than 1000
#Unless otherwise listed, all of my non-standard imports can be gotten from my pyClasses repository at https://bitbucket.org/Mattrixwv/pyClasses #Unless otherwise listed, all of my non-standard imports can be gotten from my pyClasses repository at https://bitbucket.org/Mattrixwv/pyClasses
""" """
Copyright (C) 2020 Matthew Ellison Copyright (C) 2021 Matthew Ellison
This program is free software: you can redistribute it and/or modify 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 it under the terms of the GNU Lesser General Public License as published by
@@ -23,7 +23,6 @@
from Problems.Problem import Problem from Problems.Problem import Problem
from Unsolved import Unsolved
import math import math
@@ -33,13 +32,13 @@ class Problem1(Problem):
#Functions #Functions
#Constructor #Constructor
def __init__(self): def __init__(self) -> None:
super().__init__("What is the sum of all the multiples of 3 or 5 that are less than 1000") super().__init__("What is the sum of all the multiples of 3 or 5 that are less than 1000")
self.fullSum = 0 #The sum of all the numbers self.fullSum = 0 #The sum of all the numbers
#Operational functions #Operational functions
#Solve the problem #Solve the problem
def solve(self): def solve(self) -> None:
#If the problem has already been solved do nothing and end the function #If the problem has already been solved do nothing and end the function
if(self.solved): if(self.solved):
return return
@@ -47,8 +46,10 @@ class Problem1(Problem):
#Start the timer #Start the timer
self.timer.start() self.timer.start()
#Get the sum of the progressions of 3 and 5 and remove the sum of progressions of the overlap #Get the sum of the progressions of 3 and 5 and remove the sum of progressions of the overlap
self.fullSum = self.sumOfProgression(3) + self.sumOfProgression(5) - self.sumOfProgression(3 * 5) self.fullSum = self.__sumOfProgression(3) + self.__sumOfProgression(5) - self.__sumOfProgression(3 * 5)
#Stop the timer #Stop the timer
self.timer.stop() self.timer.stop()
@@ -57,25 +58,21 @@ class Problem1(Problem):
self.solved = True self.solved = True
#Reset the problem so it can be run again #Reset the problem so it can be run again
def reset(self): def reset(self) -> None:
super().reset() super().reset()
self.fullSum = 0 self.fullSum = 0
#Gets #Gets
#Returns the result of solving the problem #Returns the result of solving the problem
def getResult(self): def getResult(self):
#If the problem hasn't been solved throw an exception self.solvedCheck("result")
if(not self.solved):
raise Unsolved("You must solve the problem before you can see the result")
return f"The sum of all numbers < {self.__topNum + 1} is {self.fullSum}" return f"The sum of all numbers < {self.__topNum + 1} is {self.fullSum}"
#Returns the requested sum #Returns the requested sum
def getSum(self) -> int: def getSum(self) -> int:
#If the problem hasn't been solved throw an exception self.solvedCheck("sum")
if(not self.solved):
raise Unsolved("You must solve the problem before can you see the sum")
return self.fullSum return self.fullSum
#Gets the sum of the progression of the multiple #Gets the sum of the progression of the multiple
def sumOfProgression(self, multiple: int) -> int: def __sumOfProgression(self, multiple: int) -> int:
numTerms = math.floor(self.__topNum / multiple) #Get the sum of the progressions of 3 and 5 and remove the sum of progressions of the overlap numTerms = math.floor(self.__topNum / multiple) #Get the sum of the progressions of 3 and 5 and remove the sum of progressions of the overlap
#The sum of progression formula is (n / 2)(a + l). n = number of terms, a = multiple, l = last term #The sum of progression formula is (n / 2)(a + l). n = number of terms, a = multiple, l = last term
return int((numTerms / 2) * (multiple + (numTerms * multiple))) return int((numTerms / 2) * (multiple + (numTerms * multiple)))

View File

@@ -1,11 +1,11 @@
#Project Euler/Python/Problem10.py #Project Euler/Python/Problem10.py
#Matthew Ellison #Matthew Ellison
# Created: 01-30-19 # Created: 01-30-19
#Modified: 10-30-20 #Modified: 07-24-21
#Find the sum of all the primes below two million #Find the sum of all the primes below two million
#Unless otherwise listed, all of my non-standard imports can be gotten from my pyClasses repository at https://bitbucket.org/Mattrixwv/pyClasses #Unless otherwise listed, all of my non-standard imports can be gotten from my pyClasses repository at https://bitbucket.org/Mattrixwv/pyClasses
""" """
Copyright (C) 2020 Matthew Ellison Copyright (C) 2021 Matthew Ellison
This program is free software: you can redistribute it and/or modify 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 it under the terms of the GNU Lesser General Public License as published by
@@ -23,8 +23,7 @@
from Problems.Problem import Problem from Problems.Problem import Problem
from Unsolved import Unsolved import NumberAlgorithms
from Algorithms import getPrimes
class Problem10(Problem): class Problem10(Problem):
@@ -33,13 +32,13 @@ class Problem10(Problem):
#Functions #Functions
#Constructor #Constructor
def __init__(self): def __init__(self) -> None:
super().__init__("Find the sum of all the primes below two million") super().__init__("Find the sum of all the primes below two million")
self.sum = 0 #The sum of all of the prime numbers self.sum = 0 #The sum of all of the prime numbers
#Operational functions #Operational functions
#Solve the function #Solve the function
def solve(self): def solve(self) -> None:
#If the problem has already been solved do nothing and end the function #If the problem has already been solved do nothing and end the function
if(self.solved): if(self.solved):
return return
@@ -47,11 +46,13 @@ class Problem10(Problem):
#Start the timer #Start the timer
self.timer.start() self.timer.start()
#Get all of the primes < 2000000 #Get all of the primes < 2000000
primes = getPrimes(self.__numberGreaterThanPrimes) primes = NumberAlgorithms.getPrimes(self.__numberGreaterThanPrimes)
#Get the sum of the list #Get the sum of the list
self.sum = sum(primes) self.sum = sum(primes)
#Stop the timer #Stop the timer
self.timer.stop() self.timer.stop()
@@ -59,22 +60,18 @@ class Problem10(Problem):
self.solved = True self.solved = True
#Reset the problem so it can be run again #Reset the problem so it can be run again
def reset(self): def reset(self) -> None:
super().reset() super().reset()
self.sum = 0 self.sum = 0
#Gets #Gets
#Returns the result of solving the problem #Returns the result of solving the problem
def getResult(self): def getResult(self) -> str:
#If the problem hasn't been solved throw an exception self.solvedCheck("result")
if(not self.solved):
raise Unsolved("You must solve the problem before you can see the result")
return f"The sum of all the prime numbers less than {self.__numberGreaterThanPrimes + 1} is {self.sum}" return f"The sum of all the prime numbers less than {self.__numberGreaterThanPrimes + 1} is {self.sum}"
#Returns the sum that was requested #Returns the sum that was requested
def getSum(self) -> int: def getSum(self) -> int:
#If the problem hasn't been solved throw an exception self.solvedCheck("sum")
if(not self.solved):
raise Unsolved("You must solve the problem before you can get the sum")
return self.sum return self.sum

View File

@@ -1,7 +1,7 @@
#ProjectEuler/Python/Problem11.py #ProjectEuler/Python/Problem11.py
#Matthew Ellison #Matthew Ellison
# Created: 01-31-19 # Created: 01-31-19
#Modified: 10-30-20 #Modified: 07-24-21
#What is the greatest product of four adjacent numbers in the same direction (up, down, left, right, or diagonally) in the 20×20 grid? #What is the greatest product of four adjacent numbers in the same direction (up, down, left, right, or diagonally) in the 20×20 grid?
""" """
08 02 22 97 38 15 00 40 00 75 04 05 07 78 52 12 50 77 91 08 08 02 22 97 38 15 00 40 00 75 04 05 07 78 52 12 50 77 91 08
@@ -27,7 +27,7 @@
""" """
#Unless otherwise listed, all of my non-standard imports can be gotten from my pyClasses repository at https://bitbucket.org/Mattrixwv/pyClasses #Unless otherwise listed, all of my non-standard imports can be gotten from my pyClasses repository at https://bitbucket.org/Mattrixwv/pyClasses
""" """
Copyright (C) 2020 Matthew Ellison Copyright (C) 2021 Matthew Ellison
This program is free software: you can redistribute it and/or modify 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 it under the terms of the GNU Lesser General Public License as published by
@@ -45,8 +45,7 @@
from Problems.Problem import Problem from Problems.Problem import Problem
from Unsolved import Unsolved from ArrayAlgorithms import prod
from Algorithms import prod
class Problem11(Problem): class Problem11(Problem):
@@ -74,13 +73,13 @@ class Problem11(Problem):
#Functions #Functions
#Constructor #Constructor
def __init__(self): def __init__(self) -> None:
super().__init__("What is the greatest product of four adjacent numbers in the same direction (up, down, left, right, or diagonally) in the 20×20 grid?") super().__init__("What is the greatest product of four adjacent numbers in the same direction (up, down, left, right, or diagonally) in the 20×20 grid?")
self.greatestProduct = [] self.greatestProduct = []
#Operational functions #Operational functions
#Solve the problem #Solve the problem
def solve(self): def solve(self) -> None:
#If the problem has already been solved do nothing and end the function #If the problem has already been solved do nothing and end the function
if(self.solved): if(self.solved):
return return
@@ -92,6 +91,7 @@ class Problem11(Problem):
#Start the timer #Start the timer
self.timer.start() self.timer.start()
#Loop through every location in the grid #Loop through every location in the grid
for row in range(0, len(self.__grid)): for row in range(0, len(self.__grid)):
for col in range (0, len(self.__grid[row])): for col in range (0, len(self.__grid[row])):
@@ -149,6 +149,7 @@ class Problem11(Problem):
if(prod(currentNumbers) > prod(self.greatestProduct)): if(prod(currentNumbers) > prod(self.greatestProduct)):
self.greatestProduct = currentNumbers.copy() self.greatestProduct = currentNumbers.copy()
#Stop the timer #Stop the timer
self.timer.stop() self.timer.stop()
@@ -156,28 +157,22 @@ class Problem11(Problem):
self.solved = True self.solved = True
#Reset the problem so it can be run again #Reset the problem so it can be run again
def reset(self): def reset(self) -> None:
super().reset() super().reset()
self.greatestProduct.clear() self.greatestProduct.clear()
#Gets #Gets
#Returns the result of solving the problem #Returns the result of solving the problem
def getResult(self): def getResult(self) -> str:
#If the problem hasn't been solved throw an exception self.solvedCheck("result")
if(not self.solved):
raise Unsolved("You must solve the problem before you can see the result")
return f"The greatest product of 3 numbers in a line is {prod(self.greatestProduct)}" return f"The greatest product of 3 numbers in a line is {prod(self.greatestProduct)}"
#Returns the numbers that were being searched #Returns the numbers that were being searched
def getNumbers(self) -> list: def getNumbers(self) -> list:
#If the problem hasn't been solved throw an exception self.solvedCheck("numbers")
if(not self.solved):
raise Unsolved("You must solve the problem before you can get the numbers being searched")
return self.greatestProduct return self.greatestProduct
#Returns the product that was requested #Returns the product that was requested
def getProduct(self) -> int: def getProduct(self) -> int:
#If the problem hasn't been solved throw an exception self.solvedCheck("product of the numbers")
if(not self.solved):
raise Unsolved("You must solve the problem before you can get the product")
return prod(self.greatestProduct) return prod(self.greatestProduct)

View File

@@ -1,11 +1,11 @@
#ProjectEuler/Python/Problem12.py #ProjectEuler/Python/Problem12.py
#Matthew Ellison #Matthew Ellison
# Created: 01-31-19 # Created: 01-31-19
#Modified: 10-30-20 #Modified: 07-24-21
#What is the value of the first triangle number to have over five hundred divisors? #What is the value of the first triangle number to have over five hundred divisors?
#Unless otherwise listed, all of my non-standard imports can be gotten from my pyClasses repository at https://bitbucket.org/Mattrixwv/pyClasses #Unless otherwise listed, all of my non-standard imports can be gotten from my pyClasses repository at https://bitbucket.org/Mattrixwv/pyClasses
""" """
Copyright (C) 2020 Matthew Ellison Copyright (C) 2021 Matthew Ellison
This program is free software: you can redistribute it and/or modify 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 it under the terms of the GNU Lesser General Public License as published by
@@ -23,8 +23,7 @@
from Problems.Problem import Problem from Problems.Problem import Problem
from Unsolved import Unsolved import NumberAlgorithms
from Algorithms import getDivisors
class Problem12(Problem): class Problem12(Problem):
@@ -33,13 +32,13 @@ class Problem12(Problem):
#Functions #Functions
#Constructor #Constructor
def __init__(self): def __init__(self) -> None:
super().__init__("What is the value of the first triangle number to have over five hundred divisors?") super().__init__("What is the value of the first triangle number to have over five hundred divisors?")
self.sum = 1 self.sum = 1
self.counter = 2 self.counter = 2
self.divisors = [] self.divisors = []
def solve(self): def solve(self) -> None:
#If the problem has already been solved do nothing and end the function #If the problem has already been solved do nothing and end the function
if(self.solved): if(self.solved):
return return
@@ -47,11 +46,12 @@ class Problem12(Problem):
#Start the timer #Start the timer
self.timer.start() self.timer.start()
#Start at the first triangular number and loop around, moving to the next, until you find one with the appropriate number of divisors #Start at the first triangular number and loop around, moving to the next, until you find one with the appropriate number of divisors
foundNumber = False #A flag for when the triangular number has over __goalDivisors divisors foundNumber = False #A flag for when the triangular number has over __goalDivisors divisors
while((not foundNumber) and (self.sum > 0)): #Make sure you haven't caused an overflow and made trianularNumber negative while((not foundNumber) and (self.sum > 0)): #Make sure you haven't caused an overflow and made trianularNumber negative
#See how many divisors this triangular number has #See how many divisors this triangular number has
self.divisors = getDivisors(self.sum) self.divisors = NumberAlgorithms.getDivisors(self.sum)
#If it did have enough raise a flag to stop the loop #If it did have enough raise a flag to stop the loop
if(len(self.divisors) > self.__goalDivisors): if(len(self.divisors) > self.__goalDivisors):
foundNumber = True foundNumber = True
@@ -59,6 +59,7 @@ class Problem12(Problem):
self.sum += self.counter #Add the next number to continue the triangular sequence self.sum += self.counter #Add the next number to continue the triangular sequence
self.counter += 1 #Advance to the next number in the triangular sequence self.counter += 1 #Advance to the next number in the triangular sequence
#Stop the timer #Stop the timer
self.timer.stop() self.timer.stop()
@@ -66,7 +67,7 @@ class Problem12(Problem):
self.solved = True self.solved = True
#Reset the problem so it can be run again #Reset the problem so it can be run again
def reset(self): def reset(self) -> None:
super().reset() super().reset()
self.sum = 1 self.sum = 1
self.counter = 2 self.counter = 2
@@ -74,34 +75,24 @@ class Problem12(Problem):
#Gets #Gets
#Returns the result of solving the problem #Returns the result of solving the problem
def getResult(self): def getResult(self) -> str:
#If the problem hasn't been solved throw an exception self.solvedCheck("result")
if(not self.solved):
raise Unsolved("You must solve the problem before you can see the result")
return f"The first triangular number with more than {self.__goalDivisors} divisors is {self.sum}" return f"The first triangular number with more than {self.__goalDivisors} divisors is {self.sum}"
#Returns the triangular number #Returns the triangular number
def getTriangularNumber(self) -> int: def getTriangularNumber(self) -> int:
#If the problem hasn't been solved throw an exception self.solvedCheck("triangular number")
if(not self.solved):
raise Unsolved("You must solve the problem before you can get the triangular number")
return self.sum return self.sum
#Gets the final number that was added to the triangular number #Gets the final number that was added to the triangular number
def getLastNumberAdded(self) -> int: def getLastNumberAdded(self) -> int:
#If the problem hasn't been solved throw an exception self.solvedCheck("last number added to get the triangular number")
if(not self.solved):
raise Unsolved("You must solve the problem before you can get the last number added to the triangular number")
return self.counter - 1 return self.counter - 1
#Returns the list of divisors of the requested number #Returns the list of divisors of the requested number
def getDivisorsOfTriangularNumber(self) -> list: def getDivisorsOfTriangularNumber(self) -> list:
#If the problem hasn't been solved throw an exception self.solvedCheck("divisors of the triangular number")
if(not self.solved):
raise Unsolved("You must solve the problem before you can get the divisors of the triangular number")
return self.divisors return self.divisors
#Returns the number of divisors of the requested number #Returns the number of divisors of the requested number
def getNumberOfDivisors(self) -> int: def getNumberOfDivisors(self) -> int:
#If the problem hasn't been solved throw an exception self.solvedCheck("number of divisors of the triangular number")
if(not self.solved):
raise Unsolved("You must solve the problem before you can get the number of divisors")
return len(self.divisors) return len(self.divisors)

View File

@@ -1,7 +1,7 @@
#ProjectEuler/Python/Problem13.py #ProjectEuler/Python/Problem13.py
#Matthew Ellison #Matthew Ellison
# Created: 01-31-19 # Created: 01-31-19
#Modified: 10-30-20 #Modified: 07-24-21
#Work out the first ten digits of the sum of the following one-hundred 50-digit numbers #Work out the first ten digits of the sum of the following one-hundred 50-digit numbers
""" """
37107287533902102798797998220837590246510135740250 37107287533902102798797998220837590246510135740250
@@ -107,7 +107,7 @@
""" """
#Unless otherwise listed, all of my non-standard imports can be gotten from my pyClasses repository at https://bitbucket.org/Mattrixwv/pyClasses #Unless otherwise listed, all of my non-standard imports can be gotten from my pyClasses repository at https://bitbucket.org/Mattrixwv/pyClasses
""" """
Copyright (C) 2020 Matthew Ellison Copyright (C) 2021 Matthew Ellison
This program is free software: you can redistribute it and/or modify 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 it under the terms of the GNU Lesser General Public License as published by
@@ -125,7 +125,6 @@
from Problems.Problem import Problem from Problems.Problem import Problem
from Unsolved import Unsolved
class Problem13(Problem): class Problem13(Problem):
@@ -233,13 +232,13 @@ class Problem13(Problem):
#Functions #Functions
#Constructor #Constructor
def __init__(self): def __init__(self) -> None:
super().__init__("Work out the first ten digits of the sum of the one-hundred 50-digit numbers") super().__init__("Work out the first ten digits of the sum of the one-hundred 50-digit numbers")
self.sum = 0 self.sum = 0
#Operational functions #Operational functions
#Solve the problem #Solve the problem
def solve(self): def solve(self) -> None:
#If the problem has already been solved do nothing and end the function #If the problem has already been solved do nothing and end the function
if(self.solved): if(self.solved):
return return
@@ -247,9 +246,11 @@ class Problem13(Problem):
#Start the timer #Start the timer
self.timer.start() self.timer.start()
#Get the sum of all of the numbers in the list #Get the sum of all of the numbers in the list
self.sum = sum(self.__numbers) self.sum = sum(self.__numbers)
#Stop the timer #Stop the timer
self.timer.stop() self.timer.stop()
@@ -257,29 +258,23 @@ class Problem13(Problem):
self.solved = True self.solved = True
#Reset the problem so it can be run again #Reset the problem so it can be run again
def reset(self): def reset(self) -> None:
super().reset() super().reset()
self.sum = 0 self.sum = 0
#Gets #Gets
#Returns the result of solving the problem #Returns the result of solving the problem
def getResult(self): def getResult(self) -> str:
#If the problem hasn't been solved throw an exception self.solvedCheck("result")
if(not self.solved):
raise Unsolved("You must solve the problem before you can see the result")
return f"The sum of all {len(self.__numbers)} numbers is {self.sum}\n" \ return f"The sum of all {len(self.__numbers)} numbers is {self.sum}\n" \
f"The first 10 digits are: {str(self.sum)[0:10]}" f"The first 10 digits are: {str(self.sum)[0:10]}"
#Returns the list of 50-digit numbers #Returns the list of 50-digit numbers
def getNumbers(self) -> list: def getNumbers(self) -> list:
#If the problem hasn't been solved throw an exception self.solvedCheck("numbers")
if(not self.solved):
raise Unsolved("You must solve the problem before you can get the numbers")
return self.__numbers return self.__numbers
#Returns the sum of the 50-digit numbers #Returns the sum of the 50-digit numbers
def getSum(self) -> int: def getSum(self) -> int:
#If the problem hasn't been solved throw an exception self.solvedCheck("sum")
if(not self.solved):
raise Unsolved("You must solve the problem before you can get the sum of the numbers")
return self.sum return self.sum

View File

@@ -1,7 +1,7 @@
#ProjectEuler/Python/Problem14.py #ProjectEuler/Python/Problem14.py
#Matthew Ellison #Matthew Ellison
# Created: 01-31-19 # Created: 01-31-19
#Modified: 10-30-20 #Modified: 07-24-21
""" """
The following iterative sequence is defined for the set of positive integers: The following iterative sequence is defined for the set of positive integers:
n → n/2 (n is even) n → n/2 (n is even)
@@ -10,7 +10,7 @@ Which starting number, under one million, produces the longest chain?
""" """
#Unless otherwise listed, all of my non-standard imports can be gotten from my pyClasses repository at https://bitbucket.org/Mattrixwv/pyClasses #Unless otherwise listed, all of my non-standard imports can be gotten from my pyClasses repository at https://bitbucket.org/Mattrixwv/pyClasses
""" """
Copyright (C) 2020 Matthew Ellison Copyright (C) 2021 Matthew Ellison
This program is free software: you can redistribute it and/or modify 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 it under the terms of the GNU Lesser General Public License as published by
@@ -28,7 +28,6 @@ Which starting number, under one million, produces the longest chain?
from Problems.Problem import Problem from Problems.Problem import Problem
from Unsolved import Unsolved
class Problem14(Problem): class Problem14(Problem):
@@ -37,14 +36,14 @@ class Problem14(Problem):
#Functions #Functions
#Constructor #Constructor
def __init__(self): def __init__(self) -> None:
super().__init__("Which starting number, under one million, produces the longest chain using the itterative sequence?") super().__init__("Which starting number, under one million, produces the longest chain using the itterative sequence?")
self.maxLength = 0 self.maxLength = 0
self.maxNum = 0 self.maxNum = 0
#Operational functions #Operational functions
#Solve the problem #Solve the problem
def solve(self): def solve(self) -> None:
#If the problem has already been solved do nothing and end the function #If the problem has already been solved do nothing and end the function
if(self.solved): if(self.solved):
return return
@@ -52,6 +51,7 @@ class Problem14(Problem):
#Start the timer #Start the timer
self.timer.start() self.timer.start()
#Loop through all number <= topNum and check them against the series #Loop through all number <= topNum and check them against the series
for currentNum in range(1, self.__topNum + 1): for currentNum in range(1, self.__topNum + 1):
currentLength = self.checkSeries(currentNum) currentLength = self.checkSeries(currentNum)
@@ -60,6 +60,7 @@ class Problem14(Problem):
self.maxLength = currentLength self.maxLength = currentLength
self.maxNum = currentNum self.maxNum = currentNum
#Stop the timer #Stop the timer
self.timer.stop() self.timer.stop()
@@ -81,29 +82,23 @@ class Problem14(Problem):
return length return length
#Reset the problem so it can be run again #Reset the problem so it can be run again
def reset(self): def reset(self) -> None:
super().reset() super().reset()
self.maxLength = 0 self.maxLength = 0
self.maxNum = 0 self.maxNum = 0
#Gets #Gets
#Returns the result of solving the problem #Returns the result of solving the problem
def getResult(self): def getResult(self) -> str:
#If the problem hasn't been solved throw an exception self.solvedCheck("result")
if(not self.solved):
raise Unsolved("You must solve the problem before you can see the result")
return f"The number {self.maxNum} produced a chain of {self.maxLength} steps" return f"The number {self.maxNum} produced a chain of {self.maxLength} steps"
#Returns the length of the requested chain #Returns the length of the requested chain
def getLength(self): def getLength(self) -> int:
#If the problem hasn't been solved throw an exception self.solvedCheck("length of the longest chain")
if(not self.solved):
raise Unsolved("You must solve the problem before you can get the length of the requested chain")
return self.maxLength return self.maxLength
#Returns the starting number of the requested chain #Returns the starting number of the requested chain
def getStartingNumber(self): def getStartingNumber(self) -> int:
#If the problem hasn't been solved throw an exception self.solvedCheck("starting number of the longest chain")
if(not self.solved):
raise Unsolved("You must solve the problem before you can get the number that started the series")
return self.maxNum return self.maxNum

View File

@@ -1,11 +1,11 @@
#ProjectEuler/Python/Problem15.py #ProjectEuler/Python/Problem15.py
#Matthew Ellison #Matthew Ellison
# Created: 01-31-19 # Created: 01-31-19
#Modified: 10-30-20 #Modified: 07-24-21
#How many routes from the top left corner to the bottom right corner are there through a 20×20 grid if you can only move right and down? #How many routes from the top left corner to the bottom right corner are there through a 20×20 grid if you can only move right and down?
#Unless otherwise listed, all of my non-standard imports can be gotten from my pyClasses repository at https://bitbucket.org/Mattrixwv/pyClasses #Unless otherwise listed, all of my non-standard imports can be gotten from my pyClasses repository at https://bitbucket.org/Mattrixwv/pyClasses
""" """
Copyright (C) 2020 Matthew Ellison Copyright (C) 2021 Matthew Ellison
This program is free software: you can redistribute it and/or modify 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 it under the terms of the GNU Lesser General Public License as published by
@@ -23,7 +23,6 @@
from Problems.Problem import Problem from Problems.Problem import Problem
from Unsolved import Unsolved
class Problem15(Problem): class Problem15(Problem):
@@ -33,13 +32,13 @@ class Problem15(Problem):
#Functions #Functions
#Constructor #Constructor
def __init__(self): def __init__(self) -> None:
super().__init__("How many routes from the top left corner to the bottom right corner are there through a 20x20 grid if you can only move right and down?") super().__init__("How many routes from the top left corner to the bottom right corner are there through a 20x20 grid if you can only move right and down?")
self.numOfRoutes = 0 self.numOfRoutes = 0
#Operational functions #Operational functions
#Solve the problem #Solve the problem
def solve(self): def solve(self) -> None:
#If the problem has already been solved do nothing and end the function #If the problem has already been solved do nothing and end the function
if(self.solved): if(self.solved):
return return
@@ -47,9 +46,11 @@ class Problem15(Problem):
#Start the timer #Start the timer
self.timer.start() self.timer.start()
#Start the recursion at the right location and catch what is returned #Start the recursion at the right location and catch what is returned
self.numOfRoutes = self.movement(0, 0) self.numOfRoutes = self.movement(0, 0)
#Stop the timer #Stop the timer
self.timer.stop() self.timer.stop()
@@ -75,22 +76,18 @@ class Problem15(Problem):
return numberMoves return numberMoves
#Reset the problem so it can be run again #Reset the problem so it can be run again
def reset(self): def reset(self) -> None:
super().reset() super().reset()
self.numOfRoutes = 0 self.numOfRoutes = 0
#Gets #Gets
#Returns the result of solving the problem #Returns the result of solving the problem
def getResult(self): def getResult(self) -> str:
#If the problem hasn't been solved throw an exception self.solvedCheck("result")
if(not self.solved):
raise Unsolved("You must solve the problem before you can see the result")
return f"The number of paths from 1 corner of a {self.__gridWidth} x {self.__gridHeight} grid to the opposite corner is {self.numOfRoutes}" return f"The number of paths from 1 corner of a {self.__gridWidth} x {self.__gridHeight} grid to the opposite corner is {self.numOfRoutes}"
#Returns the number of routes found #Returns the number of routes found
def getNumberOfRoutes(self) -> int: def getNumberOfRoutes(self) -> int:
#If the problem hasn't been solved throw an exception self.solvedCheck("number of routes")
if(not self.solved):
raise Unsolved("You must solve the problem before you can get the number of routes")
return self.numOfRoutes return self.numOfRoutes

View File

@@ -1,11 +1,11 @@
#Project Euler/Python/Problem16.py #Project Euler/Python/Problem16.py
#Matthew Ellison #Matthew Ellison
# Created: 02-03-19 # Created: 02-03-19
#Modified: 10-30-20 #Modified: 07-24-21
#What is the sum of the digits of the number 2^1000? #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 #Unless otherwise listed, all of my non-standard imports can be gotten from my pyClasses repository at https://bitbucket.org/Mattrixwv/pyClasses
""" """
Copyright (C) 2020 Matthew Ellison Copyright (C) 2021 Matthew Ellison
This program is free software: you can redistribute it and/or modify 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 it under the terms of the GNU Lesser General Public License as published by
@@ -23,7 +23,6 @@
from Problems.Problem import Problem from Problems.Problem import Problem
from Unsolved import Unsolved
class Problem16(Problem): class Problem16(Problem):
@@ -33,14 +32,14 @@ class Problem16(Problem):
#Functions #Functions
#Constructor #Constructor
def __init__(self): def __init__(self) -> None:
super().__init__("What is the sum of the digits of the number 2^1000?") super().__init__("What is the sum of the digits of the number 2^1000?")
self.num = 0 self.num = 0
self.sumOfElements = 0 self.sumOfElements = 0
#Operational functions #Operational functions
#Solve the problem #Solve the problem
def solve(self): def solve(self) -> None:
#If the problem has already been solved do nothing and end the function #If the problem has already been solved do nothing and end the function
if(self.solved): if(self.solved):
return return
@@ -48,6 +47,7 @@ class Problem16(Problem):
#Start the timer #Start the timer
self.timer.start() self.timer.start()
#Get the number #Get the number
self.num = self.__numToPower ** self.__power self.num = self.__numToPower ** self.__power
#Change the number to a string #Change the number to a string
@@ -57,40 +57,33 @@ class Problem16(Problem):
#Change the character to an int and add it to the sum #Change the character to an int and add it to the sum
self.sumOfElements += int(stringOfNum[cnt]) self.sumOfElements += int(stringOfNum[cnt])
#Stop the timer #Stop the timer
self.timer.stop() self.timer.stop()
#Save the result
self.result = str(self.__numToPower) + "^" + str(self.__power) + " = " + stringOfNum + "\nThe sum of the elements is " + str(self.sumOfElements)
#Throw a flag to show the problem is solved #Throw a flag to show the problem is solved
self.solved = True self.solved = True
#Reset the problem so it can be run again #Reset the problem so it can be run again
def reset(self): def reset(self) -> None:
super().reset() super().reset()
self.num = 0 self.num = 0
self.sumOfElements = 0 self.sumOfElements = 0
#Gets #Gets
#Returns the result of solving the problem #Returns the result of solving the problem
def getResult(self): def getResult(self) -> str:
#If the problem hasn't been solved throw an exception #If the problem hasn't been solved throw an exception
if(not self.solved): self.solvedCheck("result")
raise Unsolved("You must solve the problem before you can see the result")
return f"{self.__numToPower}^{self.__power} = {self.num}\n" \ return f"{self.__numToPower}^{self.__power} = {self.num}\n" \
f"The sum of the elements is {self.sumOfElements}" f"The sum of the elements is {self.sumOfElements}"
#Returns the number that was calculated #Returns the number that was calculated
def getNumber(self): def getNumber(self) -> int:
#If the problem hasn't been solved throw an exception self.solvedCheck("number")
if(not self.solved):
raise Unsolved("You must solve the problem before you can get the number")
return self.num return self.num
#Return the sum of digits of the number #Return the sum of digits of the number
def getSum(self): def getSum(self) -> int:
#If the problem hasn't been solved throw an exception self.solvedCheck("sum")
if(not self.solved):
raise Unsolved("You must solve the problem before you can get the sum of the digits of the number")
return self.sumOfElements return self.sumOfElements

View File

@@ -1,11 +1,11 @@
#ProjectEuler/Python/Problem17.py #ProjectEuler/Python/Problem17.py
#Matthew Ellison #Matthew Ellison
# Created: 02-04-19 # Created: 02-04-19
#Modified: 10-30-20 #Modified: 07-24-21
#If all the numbers from 1 to 1000 (one thousand) inclusive were written out in words, how many letters would be used? #If all the numbers from 1 to 1000 (one thousand) inclusive were written out in words, how many letters would be used?
#Unless otherwise listed, all of my non-standard imports can be gotten from my pyClasses repository at https://bitbucket.org/Mattrixwv/pyClasses #Unless otherwise listed, all of my non-standard imports can be gotten from my pyClasses repository at https://bitbucket.org/Mattrixwv/pyClasses
""" """
Copyright (C) 2020 Matthew Ellison Copyright (C) 2021 Matthew Ellison
This program is free software: you can redistribute it and/or modify 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 it under the terms of the GNU Lesser General Public License as published by
@@ -23,7 +23,6 @@
from Problems.Problem import Problem from Problems.Problem import Problem
from Unsolved import Unsolved
import math import math
@@ -34,13 +33,13 @@ class Problem17(Problem):
#Functions #Functions
#Constructor #Constructor
def __init__(self): def __init__(self) -> None:
super().__init__("If all the numbers from 1 (one) to 1000 (one thousand) inclusive were written out in words, how many letters would be used?") super().__init__("If all the numbers from 1 (one) to 1000 (one thousand) inclusive were written out in words, how many letters would be used?")
self.letterCount = 0 self.letterCount = 0
#Operational functions #Operational functions
#Solve the problem #Solve the problem
def solve(self): def solve(self) -> None:
#If the problem has already been solved do nothing and end the function #If the problem has already been solved do nothing and end the function
if(self.solved): if(self.solved):
return return
@@ -48,6 +47,7 @@ class Problem17(Problem):
#Start the timer #Start the timer
self.timer.start() self.timer.start()
#Start with 1 and increment #Start with 1 and increment
for num in range(self.__startNum, self.__stopNum + 1): for num in range(self.__startNum, self.__stopNum + 1):
#Pass the number to a function that will create a string for the number #Pass the number to a function that will create a string for the number
@@ -55,6 +55,7 @@ class Problem17(Problem):
#Pass the string to a function that will count the number of letters in a string, ignoring whitespace and punctuation and add the amount to the running tally #Pass the string to a function that will count the number of letters in a string, ignoring whitespace and punctuation and add the amount to the running tally
self.letterCount += self.getNumberChars(currentNumString) self.letterCount += self.getNumberChars(currentNumString)
#Stop the timer #Stop the timer
self.timer.stop() self.timer.stop()
@@ -178,22 +179,18 @@ class Problem17(Problem):
return sumOfLetters return sumOfLetters
#Reset the problem so it can be run again #Reset the problem so it can be run again
def reset(self): def reset(self) -> None:
super().reset() super().reset()
self.letterCount = 0 self.letterCount = 0
#Gets #Gets
#Returns the result of solving the problem #Returns the result of solving the problem
def getResult(self): def getResult(self) -> str:
#If the problem hasn't been solved throw an exception self.solvedCheck("result")
if(not self.solved):
raise Unsolved("You must solve the problem before you can see the result")
return f"The sum of all the letters in all the numbers {self.__startNum}-{self.__stopNum} is {self.letterCount}" return f"The sum of all the letters in all the numbers {self.__startNum}-{self.__stopNum} is {self.letterCount}"
#Returns the number of letters asked for #Returns the number of letters asked for
def getLetterCount(self): def getLetterCount(self) -> int:
#If the problem hasn't been solved throw an exception self.solvedCheck("letter count")
if(not self.solved):
raise Unsolved("You must solve the problem before you can get the number of letters")
return self.letterCount return self.letterCount

View File

@@ -1,7 +1,7 @@
#ProjectEuler/Python/Problem18.py #ProjectEuler/Python/Problem18.py
#Matthew Ellison #Matthew Ellison
# Created: 03-12-19 # Created: 03-12-19
#Modified: 10-30-20 #Modified: 07-24-21
#Find the maximum total from top to bottom #Find the maximum total from top to bottom
""" """
75 75
@@ -22,7 +22,7 @@
""" """
#Unless otherwise listed, all of my non-standard imports can be gotten from my pyClasses repository at https://bitbucket.org/Mattrixwv/pyClasses #Unless otherwise listed, all of my non-standard imports can be gotten from my pyClasses repository at https://bitbucket.org/Mattrixwv/pyClasses
""" """
Copyright (C) 2020 Matthew Ellison Copyright (C) 2021 Matthew Ellison
This program is free software: you can redistribute it and/or modify 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 it under the terms of the GNU Lesser General Public License as published by
@@ -40,7 +40,6 @@
from Problems.Problem import Problem from Problems.Problem import Problem
from Unsolved import Unsolved
from collections import namedtuple from collections import namedtuple
@@ -68,7 +67,7 @@ class Problem18(Problem):
#Functions #Functions
#Constructor #Constructor
def __init__(self): def __init__(self) -> None:
super().__init__("Find the maximum total from top to bottom") super().__init__("Find the maximum total from top to bottom")
self.foundPoints = [] #For the points that I have already found the shortest distance to self.foundPoints = [] #For the points that I have already found the shortest distance to
self.possiblePoints = [] #For the locations you are checking this round self.possiblePoints = [] #For the locations you are checking this round
@@ -76,7 +75,7 @@ class Problem18(Problem):
#Operational functions #Operational functions
#Solve the problem #Solve the problem
def solve(self): def solve(self) -> None:
#If the problem has already been solved do nothing and end the function #If the problem has already been solved do nothing and end the function
if(self.solved): if(self.solved):
return return
@@ -84,6 +83,7 @@ class Problem18(Problem):
#Start the timer #Start the timer
self.timer.start() self.timer.start()
#Invert the list so that each element = 100 - element #Invert the list so that each element = 100 - element
self.invert() self.invert()
@@ -124,6 +124,7 @@ class Problem18(Problem):
#Invert the list so it can be read again #Invert the list so it can be read again
self.invert() self.invert()
#Stop the timer #Stop the timer
self.timer.stop() self.timer.stop()
@@ -131,13 +132,13 @@ class Problem18(Problem):
self.solved = True self.solved = True
#This function turns every number in the array into (100 - num) to allow you to find the largest numbers rather than the smallest #This function turns every number in the array into (100 - num) to allow you to find the largest numbers rather than the smallest
def invert(self): def invert(self) -> None:
for rowCnt in range(0, self.__numRows): for rowCnt in range(0, self.__numRows):
for colCnt in range(0, len(self.__listNum[rowCnt])): for colCnt in range(0, len(self.__listNum[rowCnt])):
self.__listNum[rowCnt][colCnt] = 100 - self.__listNum[rowCnt][colCnt] self.__listNum[rowCnt][colCnt] = 100 - self.__listNum[rowCnt][colCnt]
#This function removes every element in listNum that is equal to loc #This function removes every element in listNum that is equal to loc
def removeIf(self, listNum: list, loc: tuple): def removeIf(self, listNum: list, loc: tuple) -> None:
location = 0 location = 0
while(location < len(listNum)): while(location < len(listNum)):
if((listNum[location].xLocation == loc.xLocation) and (listNum[location].yLocation == loc.yLocation)): if((listNum[location].xLocation == loc.xLocation) and (listNum[location].yLocation == loc.yLocation)):
@@ -146,7 +147,7 @@ class Problem18(Problem):
location += 1 location += 1
#Reset the problem so it can be run again #Reset the problem so it can be run again
def reset(self): def reset(self) -> None:
super().reset() super().reset()
self.foundPoints.clear() self.foundPoints.clear()
self.possiblePoints.clear() self.possiblePoints.clear()
@@ -154,33 +155,27 @@ class Problem18(Problem):
#Gets #Gets
#Returns the result of solving the problem #Returns the result of solving the problem
def getResult(self): def getResult(self) -> str:
#If the problem hasn't been solved throw an exception self.solvedCheck("result")
if(not self.solved):
raise Unsolved("You must solve the problem before you can see the result")
return f"The value of the longest path is {self.actualTotal}" return f"The value of the longest path is {self.actualTotal}"
#Returns the pyramid that was traversed as a string #Returns the pyramid that was traversed as a string
def getPyramid(self) -> str: def getPyramid(self) -> str:
if(not self.solved): self.solvedCheck("pyramid of numbers")
raise Unsolved("You must solve the problem before you can get the pyramid") pyramidString = ""
results = ""
#Loop through all elements of the list and print them #Loop through all elements of the list and print them
for row in self.__listNum: for row in self.__listNum:
for column in row: for column in row:
results += "{:02d}".format(column) pyramidString += "{:02d}".format(column)
results += '\n' pyramidString += '\n'
return results return pyramidString
#Returns the trail the algorithm took as a string #Returns the trail the algorithm took as a string
def getTrail(self) -> str: def getTrail(self) -> str:
if(not self.solved): self.solvedCheck("trail of the shortest path")
raise Unsolved("You must solve the problem before you can get the trail")
#TODO: Implement this #TODO: Implement this
return "" return ""
#Returns the total that was asked for #Returns the total that was asked for
def getTotal(self) -> int: def getTotal(self) -> int:
if(not self.solved): self.solvedCheck("total")
raise Unsolved("You must solve the problem before you can get the total")
return self.actualTotal return self.actualTotal

View File

@@ -1,7 +1,7 @@
#ProjectEuler/Python/Problem19.py #ProjectEuler/Python/Problem19.py
#Matthew Ellison #Matthew Ellison
# Created: 03-13-19 # Created: 03-13-19
#Modified: 10-30-20 #Modified: 07-24-21
#How many Sundays fell on the first of the month during the twentieth century (1 Jan 1901 to 31 Dec 2000)? #How many Sundays fell on the first of the month during the twentieth century (1 Jan 1901 to 31 Dec 2000)?
""" """
You are given the following information, but you may prefer to do some research for yourself. You are given the following information, but you may prefer to do some research for yourself.
@@ -16,7 +16,7 @@ A leap year occurs on any year evenly divisible by 4, but not on a century unles
""" """
#Unless otherwise listed, all of my non-standard imports can be gotten from my pyClasses repository at https://bitbucket.org/Mattrixwv/pyClasses #Unless otherwise listed, all of my non-standard imports can be gotten from my pyClasses repository at https://bitbucket.org/Mattrixwv/pyClasses
""" """
Copyright (C) 2020 Matthew Ellison Copyright (C) 2021 Matthew Ellison
This program is free software: you can redistribute it and/or modify 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 it under the terms of the GNU Lesser General Public License as published by
@@ -34,7 +34,6 @@ A leap year occurs on any year evenly divisible by 4, but not on a century unles
from Problems.Problem import Problem from Problems.Problem import Problem
from Unsolved import Unsolved
class DAYS: class DAYS:
@@ -55,13 +54,13 @@ class Problem19(Problem):
#Functions #Functions
#Constructor #Constructor
def __init__(self): def __init__(self) -> None:
super().__init__("How many Sundays fell on the first of the month during the twentieth century (1 Jan 1901 to 31 Dec 2000)?") super().__init__("How many Sundays fell on the first of the month during the twentieth century (1 Jan 1901 to 31 Dec 2000)?")
self.totalSundays = 0 #Keep track of the number of sundays self.totalSundays = 0 #Keep track of the number of sundays
#Operational functions #Operational functions
#Solve the problem #Solve the problem
def solve(self): def solve(self) -> None:
#If the problem has already been solved do nothing and end the function #If the problem has already been solved do nothing and end the function
if(self.solved): if(self.solved):
return return
@@ -69,6 +68,7 @@ class Problem19(Problem):
#Start the timer #Start the timer
self.timer.start() self.timer.start()
#Run for all years from start to end #Run for all years from start to end
for year in range(self.__startYear, self.__endYear + 1): for year in range(self.__startYear, self.__endYear + 1):
#Run for all months in the year #Run for all months in the year
@@ -80,6 +80,7 @@ class Problem19(Problem):
elif(day == DAYS.SUNDAY): elif(day == DAYS.SUNDAY):
self.totalSundays += 1 self.totalSundays += 1
#Stop the timer #Stop the timer
self.timer.stop() self.timer.stop()
@@ -168,22 +169,18 @@ class Problem19(Problem):
return False return False
#Reset the problem so it can be run again #Reset the problem so it can be run again
def reset(self): def reset(self) -> None:
super().reset() super().reset()
self.totalSundays = 0 self.totalSundays = 0
#Gets #Gets
#Returns the result of solving the problem #Returns the result of solving the problem
def getResult(self): def getResult(self) -> str:
#If the problem hasn't been solved throw an exception self.solvedCheck("result")
if(not self.solved):
raise Unsolved("You must solve the problem before you can see the result")
return f"There are {self.totalSundays} Sundays that landed on the first of the month from {self.__startYear} to {self.__endYear}" return f"There are {self.totalSundays} Sundays that landed on the first of the month from {self.__startYear} to {self.__endYear}"
#Returns the total sundays that were asked for #Returns the total sundays that were asked for
def getTotalSundays(self): def getTotalSundays(self) -> int:
#If the problem hasn't been solved throw an exception self.solvedCheck("total number of sundays")
if(not self.solved):
raise Unsolved("You must solve the problem before you can get the total sundays")
return self.totalSundays return self.totalSundays

View File

@@ -1,11 +1,11 @@
#ProjectEuler/Python/Problem2.py #ProjectEuler/Python/Problem2.py
#Matthew Ellison #Matthew Ellison
# Created: 01-26-19 # Created: 01-26-19
#Modified: 10-30-20 #Modified: 07-23-21
#The sum of the even Fibonacci numbers less than 4,000,000 #The sum of the even Fibonacci numbers less than 4,000,000
#Unless otherwise listed, all of my non-standard imports can be gotten from my pyClasses repository at https://bitbucket.org/Mattrixwv/pyClasses #Unless otherwise listed, all of my non-standard imports can be gotten from my pyClasses repository at https://bitbucket.org/Mattrixwv/pyClasses
""" """
Copyright (C) 2020 Matthew Ellison Copyright (C) 2021 Matthew Ellison
This program is free software: you can redistribute it and/or modify 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 it under the terms of the GNU Lesser General Public License as published by
@@ -23,8 +23,7 @@
from Problems.Problem import Problem from Problems.Problem import Problem
from Algorithms import getAllFib import NumberAlgorithms
from Unsolved import Unsolved
class Problem2(Problem): class Problem2(Problem):
@@ -33,13 +32,13 @@ class Problem2(Problem):
#Functions #Functions
#Constructor #Constructor
def __init__(self): def __init__(self) -> None:
super().__init__("What is the sum of the even Fibonacci numbers less than 4,000,000?") super().__init__("What is the sum of the even Fibonacci numbers less than 4,000,000?")
self.fullSum = 0 self.fullSum = 0
#Operational functions #Operational functions
#Solve the problem #Solve the problem
def solve(self): def solve(self) -> None:
#If the problem has already been solved do nothing and end the function #If the problem has already been solved do nothing and end the function
if(self.solved): if(self.solved):
return return
@@ -47,14 +46,16 @@ class Problem2(Problem):
#Start the timer #Start the timer
self.timer.start() self.timer.start()
#Get a list of all fibonacci numbers < 4,000,000 #Get a list of all fibonacci numbers < 4,000,000
fibNums = getAllFib(self.__topNumber) #Send it - 1 because it is < __topNumber fibNums = NumberAlgorithms.getAllFib(self.__topNumber)
#Step through every element in the list checking if it is even #Step through every element in the list checking if it is even
for num in fibNums: for num in fibNums:
#If the number is even add it to the running tally #If the number is even add it to the running tally
if((num % 2) == 0): if((num % 2) == 0):
self.fullSum += num self.fullSum += num
#Stop the timer #Stop the timer
self.timer.stop() self.timer.stop()
@@ -62,22 +63,18 @@ class Problem2(Problem):
self.solved = True self.solved = True
#Reset the problem #Reset the problem
def reset(self): def reset(self) -> None:
super().reset() super().reset()
self.fullSum = 0 self.fullSum = 0
#Gets #Gets
#Returns the result of solving the problem #Returns the result of solving the problem
def getResult(self): def getResult(self) -> str:
#If the problem hasn't been solved throw an exception self.solvedCheck("result")
if(not self.solved):
raise Unsolved("You must solve the problem before you can see the result")
return f"The sum of all even Fibonacci numbers less than {self.__topNumber + 1} is {self.fullSum}" return f"The sum of all even Fibonacci numbers less than {self.__topNumber + 1} is {self.fullSum}"
#Returns the requested sum #Returns the requested sum
def getSum(self) -> int: def getSum(self) -> int:
#If the problem hasn't been solved throw an exception self.solvedCheck("sum")
if(not self.solved):
raise Unsolved("You must solve the problem before can you see the sum")
return self.fullSum return self.fullSum

View File

@@ -23,7 +23,6 @@
from Problems.Problem import Problem from Problems.Problem import Problem
from Unsolved import Unsolved
class Problem20(Problem): class Problem20(Problem):
@@ -32,14 +31,14 @@ class Problem20(Problem):
#Functions #Functions
#Constructor #Constructor
def __init__(self): def __init__(self) -> None:
super().__init__("What is the sum of the digits of 100!?") super().__init__("What is the sum of the digits of 100!?")
self.num = 1 #Holds the number 100! self.num = 1 #Holds the number 100!
self.sum = 0 #The sum of the digts of num self.sum = 0 #The sum of the digts of num
#Operational functions #Operational functions
#Solve the problem #Solve the problem
def solve(self): def solve(self) -> None:
#If the problem has already been solved do nothing and end the function #If the problem has already been solved do nothing and end the function
if(self.solved): if(self.solved):
return return
@@ -47,6 +46,7 @@ class Problem20(Problem):
#Start the timer #Start the timer
self.timer.start() self.timer.start()
#Run through every number from 1 to 100 and multiply it by the current num to get 100! #Run through every number from 1 to 100 and multiply it by the current num to get 100!
for cnt in range(1, self.__top_num + 1): for cnt in range(1, self.__top_num + 1):
self.num *= cnt self.num *= cnt
@@ -57,35 +57,30 @@ class Problem20(Problem):
for char in numString: for char in numString:
self.sum += int(char) self.sum += int(char)
#Stop the timer #Stop the timer
self.timer.stop() self.timer.stop()
#Throw a flag to show the problem is solved #Throw a flag to show the problem is solved
self.solved = True self.solved = True
#Reset the problem so it can be run again #Reset the problem so it can be run again
def reset(self): def reset(self) -> None:
super().reset() super().reset()
self.num = 1 self.num = 1
self.sum = 0 self.sum = 0
#Gets #Gets
#Returns the result of solving the problem #Returns the result of solving the problem
def getResult(self): def getResult(self) -> str:
#If the problem hasn't been solved throw an exception self.solvedCheck("result")
if(not self.solved):
raise Unsolved("You must solve the problem before you can see the result")
return f"100! = {self.num}\nThe sum of the digits is: {self.sum}" return f"100! = {self.num}\nThe sum of the digits is: {self.sum}"
#Returns the number 100! #Returns the number 100!
def getNumber(self) -> int: def getNumber(self) -> int:
#If the problem hasn't been solved throw an exception self.solvedCheck("number")
if(not self.solved):
raise Unsolved("You must solve the problem before you can get the number")
return self.num return self.num
#Returns the sum of the digits of 100! #Returns the sum of the digits of 100!
def getSum(self) -> int: def getSum(self) -> int:
#If the problem hasn't been solved throw an exception self.solvedCheck("sum of the digits")
if(not self.solved):
raise Unsolved("You must solve the problem before you can get the sum")
return self.sum return self.sum

View File

@@ -1,11 +1,11 @@
#ProjectEuler/Python/Problem21.py #ProjectEuler/Python/Problem21.py
#Matthew Ellison #Matthew Ellison
# Created: 03-18-19 # Created: 03-18-19
#Modified: 10-30-20 #Modified: 07-24-21
#Evaluate the sum of all the amicable numbers under 10000 #Evaluate the sum of all the amicable numbers under 10000
#Unless otherwise listed, all of my non-standard imports can be gotten from my pyClasses repository at https://bitbucket.org/Mattrixwv/pyClasses #Unless otherwise listed, all of my non-standard imports can be gotten from my pyClasses repository at https://bitbucket.org/Mattrixwv/pyClasses
""" """
Copyright (C) 2020 Matthew Ellison Copyright (C) 2021 Matthew Ellison
This program is free software: you can redistribute it and/or modify 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 it under the terms of the GNU Lesser General Public License as published by
@@ -23,8 +23,7 @@
from Problems.Problem import Problem from Problems.Problem import Problem
from Unsolved import Unsolved import NumberAlgorithms
import Algorithms
class Problem21(Problem): class Problem21(Problem):
@@ -33,12 +32,12 @@ class Problem21(Problem):
#Functions #Functions
#Constructor #Constructor
def __init__(self): def __init__(self) -> None:
super().__init__("Evaluate the sum of all the amicable numbers under 10000") super().__init__("Evaluate the sum of all the amicable numbers under 10000")
self.divisorSum = [] #Holds the sum of the divisors of the subscript number self.divisorSum = [] #Holds the sum of the divisors of the subscript number
self.amicable = [] #Holds all amicable numbers self.amicable = [] #Holds all amicable numbers
def solve(self): def solve(self) -> None:
#If the problem has already been solved do nothing and end the function #If the problem has already been solved do nothing and end the function
if(self.solved): if(self.solved):
return return
@@ -46,10 +45,11 @@ class Problem21(Problem):
#Start the timer #Start the timer
self.timer.start() self.timer.start()
#Generate the divisors of all the numbers < 10000, get their sum, and add it to the list #Generate the divisors of all the numbers < 10000, get their sum, and add it to the list
self.divisorSum.append(0) #Start with a 0 in the [0] location self.divisorSum.append(0) #Start with a 0 in the [0] location
for cnt in range(1, self.__limit): for cnt in range(1, self.__limit):
divisors = Algorithms.getDivisors(cnt) #Get all the divisors of a number divisors = NumberAlgorithms.getDivisors(cnt) #Get all the divisors of a number
if(len(divisors) > 1): if(len(divisors) > 1):
divisors.pop() #Remove the last entry because it will be the number itself divisors.pop() #Remove the last entry because it will be the number itself
self.divisorSum.append(int(sum(divisors))) self.divisorSum.append(int(sum(divisors)))
@@ -67,6 +67,7 @@ class Problem21(Problem):
#Add the number to the amicable vector #Add the number to the amicable vector
self.amicable.append(cnt) self.amicable.append(cnt)
#Stop the timer #Stop the timer
self.timer.stop() self.timer.stop()
@@ -74,18 +75,15 @@ class Problem21(Problem):
self.solved = True self.solved = True
#Reset the problem so it can be run again #Reset the problem so it can be run again
def reset(self): def reset(self) -> None:
super().reset() super().reset()
self.divisorSum.clear() self.divisorSum.clear()
self.amicable.clear() self.amicable.clear()
#Gets #Gets
#Returns the result of solving the problem #Returns the result of solving the problem
def getResult(self): def getResult(self) -> str:
#If the problem hasn't been solved throw an exception self.solvedCheck("result")
if(not self.solved):
raise Unsolved("You must solve the problem before you can see the result")
result = "All amicable numbers less than 10000 are\n" result = "All amicable numbers less than 10000 are\n"
for num in self.amicable: for num in self.amicable:
result += f"{num}\n" result += f"{num}\n"
@@ -94,15 +92,11 @@ class Problem21(Problem):
return result return result
#Returns a vector with all of the amicable number calculated #Returns a vector with all of the amicable number calculated
def getAmicable(self) -> list: def getAmicable(self) -> list:
#If the problem hasn't been solved throw an exception self.solvedCheck("amicable numbers")
if(not self.solved):
raise Unsolved("You must solve the problem before you can get the amicable numbers")
return self.amicable return self.amicable
#Returns the sum of all of the amicable numbers #Returns the sum of all of the amicable numbers
def getSum(self) -> int: def getSum(self) -> int:
#If the problem hasn't been solved throw an exception self.solvedCheck("sum of the amicable numbers")
if(not self.solved):
raise Unsolved("You must solve the problem before you can get the sum of the amicable numbers")
return sum(self.amicable) return sum(self.amicable)

View File

@@ -1,11 +1,11 @@
#ProjectEuler/Python/Problem22.py #ProjectEuler/Python/Problem22.py
#Matthew Ellison #Matthew Ellison
# Created: 03-20-19 # Created: 03-20-19
#Modified: 10-30-20 #Modified: 07-24-21
#What is the total of all the name scores in the file? #What is the total of all the name scores in the file?
#Unless otherwise listed, all of my non-standard imports can be gotten from my pyClasses repository at https://bitbucket.org/Mattrixwv/pyClasses #Unless otherwise listed, all of my non-standard imports can be gotten from my pyClasses repository at https://bitbucket.org/Mattrixwv/pyClasses
""" """
Copyright (C) 2020 Matthew Ellison Copyright (C) 2021 Matthew Ellison
This program is free software: you can redistribute it and/or modify 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 it under the terms of the GNU Lesser General Public License as published by
@@ -23,7 +23,6 @@
from Problems.Problem import Problem from Problems.Problem import Problem
from Unsolved import Unsolved
class Problem22(Problem): class Problem22(Problem):
@@ -399,14 +398,14 @@ class Problem22(Problem):
#Functions #Functions
#Constructor #Constructor
def __init__(self): def __init__(self) -> None:
super().__init__("What is the total of all the name scores in this file?") super().__init__("What is the total of all the name scores in this file?")
self.sums = [] #Holds the score based on the sum of the characters in the name self.sums = [] #Holds the score based on the sum of the characters in the name
self.prod = [] #Holds the score based on the sum of the characters and the location in alphabetical order self.prod = [] #Holds the score based on the sum of the characters and the location in alphabetical order
#Operational functions #Operational functions
#Solve the problem #Solve the problem
def solve(self): def solve(self) -> None:
#If the problem has already been solved do nothing and end the function #If the problem has already been solved do nothing and end the function
if(self.solved): if(self.solved):
return return
@@ -414,6 +413,7 @@ class Problem22(Problem):
#Start the timer #Start the timer
self.timer.start() self.timer.start()
#Sort all the names #Sort all the names
self.__names.sort() self.__names.sort()
#Step through every name adding up the values of the characters #Step through every name adding up the values of the characters
@@ -428,6 +428,7 @@ class Problem22(Problem):
for cnt in range(0, len(self.sums)): for cnt in range(0, len(self.sums)):
self.prod.append(self.sums[cnt] * (cnt + 1)) self.prod.append(self.sums[cnt] * (cnt + 1))
#Stop the timer #Stop the timer
self.timer.stop() self.timer.stop()
@@ -435,26 +436,22 @@ class Problem22(Problem):
self.solved = True self.solved = True
#Reset the problem so it can be run again #Reset the problem so it can be run again
def reset(self): def reset(self) -> None:
super().reset() super().reset()
self.sums.clear() self.sums.clear()
self.prod.clear() self.prod.clear()
#Gets #Gets
#Returns the result of solving the problem #Returns the result of solving the problem
def getResult(self): def getResult(self) -> str:
#If the problem hasn't been solved throw an exception self.solvedCheck("result")
if(not self.solved):
raise Unsolved("You must solve the problem before you can see the result")
return f"The answer to the question is {sum(self.prod)}" return f"The answer to the question is {sum(self.prod)}"
#Returns the vecot of the names being scored #Returns the vecot of the names being scored
def getNames(self) -> list: def getNames(self) -> list:
return self.__names return self.__names
#Returns the sum of the names scores #Returns the sum of the names scores
def getNameScoreSum(self) -> int: def getNameScoreSum(self) -> int:
#If the problem hasn't been solved throw an exception self.solvedCheck("score of the names")
if(not self.solved):
raise Unsolved("You must solve the problem before can you see the sum")
return sum(self.prod) return sum(self.prod)

View File

@@ -1,11 +1,11 @@
#ProjectEuler/Python/Problem23.py #ProjectEuler/Python/Problem23.py
#Matthew Ellison #Matthew Ellison
# Created: 03-22-19 # Created: 03-22-19
#Modified: 10-30-20 #Modified: 07-24-21
#Find the sum of all the positive integers which cannot be written as the sum of two abundant numbers #Find the sum of all the positive integers which cannot be written as the sum of two abundant numbers
#All of my imports can be gotten from my pyClasses repository at https://bitbucket.org/Mattrixwv/pyClasses #All of my imports can be gotten from my pyClasses repository at https://bitbucket.org/Mattrixwv/pyClasses
""" """
Copyright (C) 2020 Matthew Ellison Copyright (C) 2021 Matthew Ellison
This program is free software: you can redistribute it and/or modify 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 it under the terms of the GNU Lesser General Public License as published by
@@ -23,8 +23,7 @@
from Problems.Problem import Problem from Problems.Problem import Problem
from Unsolved import Unsolved import NumberAlgorithms
import Algorithms
class Problem23(Problem): class Problem23(Problem):
@@ -33,7 +32,7 @@ class Problem23(Problem):
#Functions #Functions
#Constructor #Constructor
def __init__(self): def __init__(self) -> None:
super().__init__("Find the sum of all the positive integers which cannot be written as the sum of two abundant numbers") super().__init__("Find the sum of all the positive integers which cannot be written as the sum of two abundant numbers")
self.divisorSums = [] self.divisorSums = []
self.reserveArray() self.reserveArray()
@@ -41,7 +40,7 @@ class Problem23(Problem):
#Operational functions #Operational functions
#Solve the problem #Solve the problem
def solve(self): def solve(self) -> None:
#If the problem has already been solved do nothing and end the function #If the problem has already been solved do nothing and end the function
if(self.solved): if(self.solved):
return return
@@ -49,9 +48,10 @@ class Problem23(Problem):
#Start the timer #Start the timer
self.timer.start() self.timer.start()
#Get the sum of the divisors of all numbers < __maxNum #Get the sum of the divisors of all numbers < __maxNum
for cnt in range(1, self.__maxNum): for cnt in range(1, self.__maxNum):
div = Algorithms.getDivisors(cnt) div = NumberAlgorithms.getDivisors(cnt)
if(len(div) > 1): if(len(div) > 1):
div.remove(div[len(div) - 1]) div.remove(div[len(div) - 1])
self.divisorSums[cnt] = sum(div) self.divisorSums[cnt] = sum(div)
@@ -68,15 +68,16 @@ class Problem23(Problem):
if(not self.isSum(abund, cnt)): if(not self.isSum(abund, cnt)):
self.sum += cnt self.sum += cnt
#Stop the timer #Stop the timer
self.timer.stop() self.timer.stop()
#Throw a flag to show the problem is solved #Throw a flag to show the problem is solved
self.solved = True self.solved = True
#Reserve the size of the array to speed up insertion #Reserve the size of the array to speed up insertion
def reserveArray(self): def reserveArray(self) -> None:
#Make sure every element has a 0 in it's location #Make sure every element has a 0 in it's location
for cnt in range(0, self.__maxNum): for _ in range(0, self.__maxNum):
self.divisorSums.append(0) self.divisorSums.append(0)
#A function that returns true if num can be created by adding two elements from abund and false if it cannot #A function that returns true if num can be created by adding two elements from abund and false if it cannot
def isSum(self, abund: list, num: int) -> bool: def isSum(self, abund: list, num: int) -> bool:
@@ -93,7 +94,7 @@ class Problem23(Problem):
#If you have run through the entire list and did not find a sum then it is false #If you have run through the entire list and did not find a sum then it is false
return False return False
#Reset the problem so it can be run again #Reset the problem so it can be run again
def reset(self): def reset(self) -> None:
super().reset() super().reset()
self.divisorSums.clear() self.divisorSums.clear()
self.reserveArray() self.reserveArray()
@@ -101,16 +102,12 @@ class Problem23(Problem):
#Gets #Gets
#Returns the result of solving the problem #Returns the result of solving the problem
def getResult(self): def getResult(self) -> str:
#If the problem hasn't been solved throw an exception self.solvedCheck("result")
if(not self.solved):
raise Unsolved("You must solve the problem before you can see the result")
return f"The answer is {self.sum}" return f"The answer is {self.sum}"
#Returns the sum of the numbers asked for #Returns the sum of the numbers asked for
def getSum(self) -> int: def getSum(self) -> int:
#If the problem hasn't been solved throw an exception self.solvedCheck("sum")
if(not self.solved):
raise Unsolved("You must solve the problem before can you see the sum")
return self.sum return self.sum

View File

@@ -1,11 +1,11 @@
#ProjectEuler/Python/Problem24.py #ProjectEuler/Python/Problem24.py
#Matthew Ellison #Matthew Ellison
# Created: 03-24-19 # Created: 03-24-19
#Modified: 10-30-20 #Modified: 07-24-21
#What is the millionth lexicographic permutation of the digits 0, 1, 2, 3, 4, 5, 6, 7, 8 and 9? #What is the millionth lexicographic permutation of the digits 0, 1, 2, 3, 4, 5, 6, 7, 8 and 9?
#Unless otherwise listed, all of my non-standard imports can be gotten from my pyClasses repository at https://bitbucket.org/Mattrixwv/pyClasses #Unless otherwise listed, all of my non-standard imports can be gotten from my pyClasses repository at https://bitbucket.org/Mattrixwv/pyClasses
""" """
Copyright (C) 2020 Matthew Ellison Copyright (C) 2021 Matthew Ellison
This program is free software: you can redistribute it and/or modify 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 it under the terms of the GNU Lesser General Public License as published by
@@ -23,8 +23,7 @@
from Problems.Problem import Problem from Problems.Problem import Problem
from Unsolved import Unsolved import StringAlgorithms
import Algorithms
class Problem24(Problem): class Problem24(Problem):
@@ -34,13 +33,13 @@ class Problem24(Problem):
#Functions #Functions
#Constructor #Constructor
def __init__(self): def __init__(self) -> None:
super().__init__("What is the millionth lexicographic permutation of the digits 0, 1, 2, 3, 4, 5, 6, 7, 8 and 9?") super().__init__("What is the millionth lexicographic permutation of the digits 0, 1, 2, 3, 4, 5, 6, 7, 8 and 9?")
self.permutations = [] self.permutations = []
#Operational functions #Operational functions
#Solve the problem #Solve the problem
def solve(self): def solve(self) -> None:
#If the problem has already been solved do nothing and end the function #If the problem has already been solved do nothing and end the function
if(self.solved): if(self.solved):
return return
@@ -48,8 +47,10 @@ class Problem24(Problem):
#Start the timer #Start the timer
self.timer.start() self.timer.start()
#Get all permutations of the string #Get all permutations of the string
self.permutations = Algorithms.getPermutations(self.__nums) self.permutations = StringAlgorithms.getPermutations(self.__nums)
#Stop the timer #Stop the timer
self.timer.stop() self.timer.stop()
@@ -58,32 +59,25 @@ class Problem24(Problem):
self.solved = True self.solved = True
#Reset the problem so it can be run again #Reset the problem so it can be run again
def reset(self): def reset(self) -> None:
super().reset() super().reset()
self.permutations.clear() self.permutations.clear()
#Gets #Gets
#Returns the result of solving the problem #Returns the result of solving the problem
def getResult(self): def getResult(self) -> str:
#If the problem hasn't been solved throw an exception self.solvedCheck("result")
if(not self.solved):
raise Unsolved("You must solve the problem before you can see the result")
return f"The 1 millionth permutation is {self.permutations[self.__neededPerm - 1]}" return f"The 1 millionth permutation is {self.permutations[self.__neededPerm - 1]}"
#Returns a list with all of the permutations #Returns a list with all of the permutations
def getPermutationsList(self) -> list: def getPermutationsList(self) -> list:
#If the problem hasn't been solved throw an exception self.solvedCheck("permutations")
if(not self.solved):
raise Unsolved("You must solve the problem before can you see the list of permutations")
return self.permutations return self.permutations
#Returns the requested permutation #Returns the requested permutation
def getPermutation(self) -> str: def getPermutation(self) -> str:
#If the problem hasn't been solved throw an exception self.solvedCheck("1,000,000th permutation")
if(not self.solved):
raise Unsolved("You must solve the problem before can you see the ")
return self.permutations[self.__neededPerm - 1] return self.permutations[self.__neededPerm - 1]
""" Results: """ Results:
The 1 millionth permutation is 2783915460 The 1 millionth permutation is 2783915460
It took an average of 7.147 seconds to run this problem through 100 iterations It took an average of 7.147 seconds to run this problem through 100 iterations

View File

@@ -23,8 +23,7 @@
from Problems.Problem import Problem from Problems.Problem import Problem
from Unsolved import Unsolved import NumberAlgorithms
import Algorithms
class Problem25(Problem): class Problem25(Problem):
@@ -33,14 +32,14 @@ class Problem25(Problem):
#Functions #Functions
#Constructor #Constructor
def __init__(self): def __init__(self) -> None:
super().__init__("What is the index of the first term in the Fibonacci sequence to contain 1000 digits?") super().__init__("What is the index of the first term in the Fibonacci sequence to contain 1000 digits?")
self.number = 0 #The current Fibonacci number self.number = 0 #The current Fibonacci number
self.index = 2 #The index of the current Fibonacci number just calculated self.index = 2 #The index of the current Fibonacci number just calculated
#Operational functions #Operational functions
#Sovle the problem #Sovle the problem
def solve(self): def solve(self) -> None:
#If the problem has already been solved do nothing and end the function #If the problem has already been solved do nothing and end the function
if(self.solved): if(self.solved):
return return
@@ -48,10 +47,12 @@ class Problem25(Problem):
#Start the timer #Start the timer
self.timer.start() self.timer.start()
#Move through all Fibonacci numbers until you reach the one with at least __numDigits digits #Move through all Fibonacci numbers until you reach the one with at least __numDigits digits
while(len(str(self.number)) < self.__numDigits): while(len(str(self.number)) < self.__numDigits):
self.index += 1 #Increase the index number. Doing this at the beginning keeps the index correct at the end of the loop self.index += 1 #Increase the index number. Doing this at the beginning keeps the index correct at the end of the loop
self.number = Algorithms.getFib(self.index) #Calculate the number self.number = NumberAlgorithms.getFib(self.index) #Calculate the number
#Stop the timer #Stop the timer
self.timer.stop() self.timer.stop()
@@ -60,30 +61,24 @@ class Problem25(Problem):
self.solved = True self.solved = True
#Reset the problem so it can be run again #Reset the problem so it can be run again
def reset(self): def reset(self) -> None:
super().reset() super().reset()
self.number = 0 self.number = 0
self.index = 2 self.index = 2
#Gets #Gets
#Returns the result of solving the problem #Returns the result of solving the problem
def getResult(self): def getResult(self) -> str:
#If the problem hasn't been solved throw an exception self.solvedCheck("result")
if(not self.solved):
raise Unsolved("You must solve the problem before you can see the result")
return f"The first Fibonacci number with {self.__numDigits} digits is {self.number}\n" \ return f"The first Fibonacci number with {self.__numDigits} digits is {self.number}\n" \
f"Its index is {self.index}" f"Its index is {self.index}"
#Returns the Fibonacci number asked for #Returns the Fibonacci number asked for
def getNumber(self) -> int: def getNumber(self) -> int:
#If the problem hasn't been solved throw an exception self.solvedCheck("fibonacci number")
if(not self.solved):
raise Unsolved("You must solve the problem before can you see the Fibonacci number")
return self.number return self.number
#Returns the index of the requested Fibonacci number #Returns the index of the requested Fibonacci number
def getIndex(self) -> int: def getIndex(self) -> int:
#If the problem hasn't been solved throw an exception self.solvedCheck("index of the fibonacci number")
if(not self.solved):
raise Unsolved("You must solve the problem before can you see the index of the Fibonacci number")
return self.index return self.index

View File

@@ -1,11 +1,11 @@
#ProjectEuler/Python/Problem26.py #ProjectEuler/Python/Problem26.py
#Matthew Ellison #Matthew Ellison
# Created: 07-29-19 # Created: 07-29-19
#Modified: 10-30-20 #Modified: 07-24-21
#Find the value of d < 1000 for which 1/d contains the longest recurring cycle in its decimal fraction part. #Find the value of d < 1000 for which 1/d contains the longest recurring cycle in its decimal fraction part.
#Unless otherwise listed, all of my non-standard imports can be gotten from my pyClasses repository at https://bitbucket.org/Mattrixwv/pyClasses #Unless otherwise listed, all of my non-standard imports can be gotten from my pyClasses repository at https://bitbucket.org/Mattrixwv/pyClasses
""" """
Copyright (C) 2020 Matthew Ellison Copyright (C) 2021 Matthew Ellison
This program is free software: you can redistribute it and/or modify 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 it under the terms of the GNU Lesser General Public License as published by
@@ -23,7 +23,6 @@
from Problems.Problem import Problem from Problems.Problem import Problem
from Unsolved import Unsolved
class Problem26(Problem): class Problem26(Problem):
@@ -32,14 +31,14 @@ class Problem26(Problem):
#Function #Function
#Constructor #Constructor
def __init__(self): def __init__(self) -> None:
super().__init__("Find the value of d < 1000 for which 1/d contains the longest recurring cycle in its decimal fraction part.") super().__init__("Find the value of d < 1000 for which 1/d contains the longest recurring cycle in its decimal fraction part.")
self.longestCycle = 0 self.longestCycle = 0
self.longestNumber = 0 self.longestNumber = 0
#Operational function #Operational function
#Solve the problem #Solve the problem
def solve(self): def solve(self) -> None:
#If the problem has already been solved do nothing and end the function #If the problem has already been solved do nothing and end the function
if(self.solved): if(self.solved):
return return
@@ -47,6 +46,7 @@ class Problem26(Problem):
#Start the timer #Start the timer
self.timer.start() self.timer.start()
#Start with 1/2 and find out how long the longest cycle is by checking the remainders #Start with 1/2 and find out how long the longest cycle is by checking the remainders
#Loop through every number from 2-999 and use it for the denominator #Loop through every number from 2-999 and use it for the denominator
for denominator in range(2, self.__topNumber): for denominator in range(2, self.__topNumber):
@@ -79,6 +79,7 @@ class Problem26(Problem):
self.longestCycle = len(remainderList) self.longestCycle = len(remainderList)
self.longestNumber = denominator self.longestNumber = denominator
#Stop the timer #Stop the timer
self.timer.stop() self.timer.stop()
@@ -86,30 +87,24 @@ class Problem26(Problem):
self.solved = True self.solved = True
#Reset the problem so it can be run again #Reset the problem so it can be run again
def reset(self): def reset(self) -> None:
super().reset() super().reset()
self.longestCycle = 0 self.longestCycle = 0
self.longestNumber = 0 self.longestNumber = 0
#Gets #Gets
#Returns the result of solving the problem #Returns the result of solving the problem
def getResult(self): def getResult(self) -> str:
#If the problem hasn't been solved throw an exception self.solvedCheck("result")
if(not self.solved):
raise Unsolved("You must solve the problem before you can see the result")
return f"The longest cycle is {self.longestCycle} digits long\n" \ return f"The longest cycle is {self.longestCycle} digits long\n" \
f"It is started with the number {self.longestNumber}" f"It is started with the number {self.longestNumber}"
#Returns the length of the longest cycle #Returns the length of the longest cycle
def getLongestCycle(self) -> int: def getLongestCycle(self) -> int:
#If the problem hasn't been solved throw an exception self.solvedCheck("length of the longest cycle")
if(not self.solved):
raise Unsolved("You must solve the problem before can you see the length of the longest cycle")
return self.longestCycle return self.longestCycle
#Returns the denominator that starts the longest cycle #Returns the denominator that starts the longest cycle
def getLongestNumber(self) -> int: def getLongestNumber(self) -> int:
#If the problem hasn't been solved throw an exception self.solvedCheck("denominator that starts the longest cycle")
if(not self.solved):
raise Unsolved("You must solve the problem before can you see the denominaotr that started the cycle")
return self.longestNumber return self.longestNumber

View File

@@ -1,7 +1,7 @@
#ProjectEuler/Python/Problem27.py #ProjectEuler/Python/Problem27.py
#Matthew Ellison #Matthew Ellison
# Created: 09-15-19 # Created: 09-15-19
#Modified: 10-30-20 #Modified: 07-24-21
#Find the product of the coefficients, |a| < 1000 and |b| <= 1000, for the quadratic expression that produces the maximum number of primes for consecutive values of n, starting with n=0. #Find the product of the coefficients, |a| < 1000 and |b| <= 1000, for the quadratic expression that produces the maximum number of primes for consecutive values of n, starting with n=0.
#Unless otherwise listed, all of my non-standard imports can be gotten from my pyClasses repository at https://bitbucket.org/Mattrixwv/pyClasses #Unless otherwise listed, all of my non-standard imports can be gotten from my pyClasses repository at https://bitbucket.org/Mattrixwv/pyClasses
""" """
@@ -23,14 +23,13 @@
from Problems.Problem import Problem from Problems.Problem import Problem
from Unsolved import Unsolved import NumberAlgorithms
import Algorithms
class Problem27(Problem): class Problem27(Problem):
#Functions #Functions
#Constructor #Constructor
def __init__(self): def __init__(self) -> None:
super().__init__("Find the product of the coefficients, |a| < 1000 and |b| <= 1000, for the quadratic expression that produces the maximum number of primes for consecutive values of n, starting with n=0") super().__init__("Find the product of the coefficients, |a| < 1000 and |b| <= 1000, for the quadratic expression that produces the maximum number of primes for consecutive values of n, starting with n=0")
self.topA = 0 #The A for the most n's generated self.topA = 0 #The A for the most n's generated
self.topB = 0 #The B for the most n's generated self.topB = 0 #The B for the most n's generated
@@ -39,7 +38,7 @@ class Problem27(Problem):
#Operational functions #Operational functions
#Solve the problem #Solve the problem
def solve(self): def solve(self) -> None:
#If the problem has already been solved do nothing and end the function #If the problem has already been solved do nothing and end the function
if(self.solved): if(self.solved):
return return
@@ -47,8 +46,9 @@ class Problem27(Problem):
#Start the timer #Start the timer
self.timer.start() self.timer.start()
#Get the primes #Get the primes
primes = Algorithms.getPrimes(12000) #A list of all primes that could possibly be generated with this formula primes = NumberAlgorithms.getPrimes(12000) #A list of all primes that could possibly be generated with this formula
#Start with the lowest possible A and check all possibilities after that #Start with the lowest possible A and check all possibilities after that
for a in range(-999, 999): for a in range(-999, 999):
#Start with the lowest possible B and check all possibilities after that #Start with the lowest possible B and check all possibilities after that
@@ -67,6 +67,7 @@ class Problem27(Problem):
self.topB = b self.topB = b
self.topA = a self.topA = a
#Stop the timer #Stop the timer
self.timer.stop() self.timer.stop()
@@ -79,7 +80,7 @@ class Problem27(Problem):
self.solved = True self.solved = True
#Reset the problem so it can be run again #Reset the problem so it can be run again
def reset(self): def reset(self) -> None:
super().reset() super().reset()
self.topA = 0 self.topA = 0
self.topB = 0 self.topB = 0
@@ -88,34 +89,31 @@ class Problem27(Problem):
#Gets #Gets
#Returns the result of solving the problem #Returns the result of solving the problem
def getResult(self): def getResult(self) -> str:
#If the problem hasn't been solved throw an exception self.solvedCheck("result")
if(not self.solved):
raise Unsolved("You must solve the problem before you can see the result")
return f"The greatest number of primes found is {self.topN}\n" \ return f"The greatest number of primes found is {self.topN}\n" \
f"It was found with A = {self.topA}, B = {self.topB}\n" \ f"It was found with A = {self.topA}, B = {self.topB}\n" \
f"The product of A and B is {self.topA * self.topB}" f"The product of A and B is {self.topA * self.topB}"
#Returns the top A that was generated #Returns the top A that was generated
def getTopA(self) -> int: def getTopA(self) -> int:
#If the problem hasn't been solved throw an exception self.solvedCheck("largest A")
if(not self.solved):
raise Unsolved("You must solve the problem before can you see the top A")
return self.topA return self.topA
#Returns the top B that was generated #Returns the top B that was generated
def getTopB(self) -> int: def getTopB(self) -> int:
#If the problem hasn't been solved throw an exception self.solvedCheck("largest B")
if(not self.solved):
raise Unsolved("You must solve the problem before can you see the top B")
return self.topA return self.topA
#Returns the top N that was generated #Returns the top N that was generated
def getTopN(self) -> int: def getTopN(self) -> int:
#If the problem hasn't been solved throw an exception self.solvedCheck("largest N")
if(not self.solved):
raise Unsolved("You must solve the problem before can you see the top N")
return self.topA return self.topA
#Returns the product of A and B for the answer
def getProduct(self) -> int:
self.solvedCheck("product of A and B")
return self.topA * self.topB
""" Results: """ Results:
The greatest number of primes found is 70 The greatest number of primes found is 70

View File

@@ -1,11 +1,11 @@
#ProjectEuler/Python/Problem28.py #ProjectEuler/Python/Problem28.py
#Matthew Ellison #Matthew Ellison
# Created: 09-22-19 # Created: 09-22-19
#Modified: 10-30-20 #Modified: 07-24-21
#What is the sum of the numbers on the diagonals in a 1001 by 1001 spiral formed by starting with the number 1 and moving to the right in a clockwise direction a 5 by 5 spiral #What is the sum of the numbers on the diagonals in a 1001 by 1001 spiral formed by starting with the number 1 and moving to the right in a clockwise direction a 5 by 5 spiral
#Unless otherwise listed, all of my non-standard imports can be gotten from my pyClasses repository at https://bitbucket.org/Mattrixwv/pyClasses #Unless otherwise listed, all of my non-standard imports can be gotten from my pyClasses repository at https://bitbucket.org/Mattrixwv/pyClasses
""" """
Copyright (C) 2020 Matthew Ellison Copyright (C) 2021 Matthew Ellison
This program is free software: you can redistribute it and/or modify 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 it under the terms of the GNU Lesser General Public License as published by
@@ -23,7 +23,6 @@
from Problems.Problem import Problem from Problems.Problem import Problem
from Unsolved import Unsolved
class Problem28(Problem): class Problem28(Problem):
@@ -31,13 +30,13 @@ class Problem28(Problem):
grid = [] grid = []
#Functions #Functions
#Constructor #Constructor
def __init__(self): def __init__(self) -> None:
super().__init__("What is the sum of the numbers on the diagonals in a 1001 by 1001 spiral formed by starting with the number 1 and moving to the right in a clockwise direction?") super().__init__("What is the sum of the numbers on the diagonals in a 1001 by 1001 spiral formed by starting with the number 1 and moving to the right in a clockwise direction?")
self.sumOfDiagonals = 0 self.sumOfDiagonals = 0
#Operational functions #Operational functions
#Solve the problem #Solve the problem
def solve(self): def solve(self) -> None:
#If the problem has already been solved do nothing and end the function #If the problem has already been solved do nothing and end the function
if(self.solved): if(self.solved):
return return
@@ -45,11 +44,13 @@ class Problem28(Problem):
#Start the timer #Start the timer
self.timer.start() self.timer.start()
#Setup the grid #Setup the grid
self.grid = self.setupGrid() self.grid = self.setupGrid()
#Find the sum of the diagonals in the grid #Find the sum of the diagonals in the grid
self.sumOfDiagonals = self.findSum() self.sumOfDiagonals = self.findSum()
#Stop the timer #Stop the timer
self.timer.stop() self.timer.stop()
@@ -120,25 +121,21 @@ class Problem28(Problem):
return sumOfDiagonals return sumOfDiagonals
#Reset the problem so it can be run again #Reset the problem so it can be run again
def reset(self): def reset(self) -> None:
super().reset() super().reset()
self.sumOfDiagonals = 0 self.sumOfDiagonals = 0
#Gets #Gets
#Returns the result of solving the problem #Returns the result of solving the problem
def getResult(self): def getResult(self) -> str:
#If the problem hasn't been solved throw an exception self.solvedCheck("result")
if(not self.solved):
raise Unsolved("You must solve the problem before you can see the result")
return f"The sum of the diagonals in the given grid is {self.sumOfDiagonals}" return f"The sum of the diagonals in the given grid is {self.sumOfDiagonals}"
#Returns the grid #Returns the grid
def getGrid(self) -> list: def getGrid(self) -> list:
return self.grid return self.grid
#Returns the sum of the diagonals #Returns the sum of the diagonals
def getSum(self) -> int: def getSum(self) -> int:
#If the problem hasn't been solved throw an exception self.solvedCheck("sum")
if(not self.solved):
raise Unsolved("You must solve the problem before can you see the sum")
return self.sumOfDiagonals return self.sumOfDiagonals

View File

@@ -1,11 +1,11 @@
#ProjectEuler/Python/Problem29.py #ProjectEuler/Python/Problem29.py
#Matthew Ellison #Matthew Ellison
# Created: 10-10-19 # Created: 10-10-19
#Modified: 10-30-20 #Modified: 07-24-21
#How many distinct terms are in the sequence generated by a^b for 2 <= a <= 100 and 2 <= b <= 100? #How many distinct terms are in the sequence generated by a^b for 2 <= a <= 100 and 2 <= b <= 100?
#Unless otherwise listed, all of my non-standard imports can be gotten from my pyClasses repository at https://bitbucket.org/Mattrixwv/pyClasses #Unless otherwise listed, all of my non-standard imports can be gotten from my pyClasses repository at https://bitbucket.org/Mattrixwv/pyClasses
""" """
Copyright (C) 2020 Matthew Ellison Copyright (C) 2021 Matthew Ellison
This program is free software: you can redistribute it and/or modify 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 it under the terms of the GNU Lesser General Public License as published by
@@ -23,7 +23,6 @@
from Problems.Problem import Problem from Problems.Problem import Problem
from Unsolved import Unsolved
class Problem29(Problem): class Problem29(Problem):
@@ -35,13 +34,13 @@ class Problem29(Problem):
#Functions #Functions
#Constructor #Constructor
def __init__(self): def __init__(self) -> None:
super().__init__("How many distinct terms are in the sequence generated by a^b for 2 <= a <= 100 and 2 <= b <= 100?") super().__init__("How many distinct terms are in the sequence generated by a^b for 2 <= a <= 100 and 2 <= b <= 100?")
self.unique = [] self.unique = []
#Operational functions #Operational functions
#Solve the problem #Solve the problem
def solve(self): def solve(self) -> None:
#If the problem has already been solved do nothing and end the function #If the problem has already been solved do nothing and end the function
if(self.solved): if(self.solved):
return return
@@ -49,6 +48,7 @@ class Problem29(Problem):
#Start the timer #Start the timer
self.timer.start() self.timer.start()
#Start with the first A and move towards the top #Start with the first A and move towards the top
for currentA in range(self.__bottomA, self.__topA + 1): for currentA in range(self.__bottomA, self.__topA + 1):
#Start with the first B and move towards the top #Start with the first B and move towards the top
@@ -59,6 +59,7 @@ class Problem29(Problem):
if currentNum not in self.unique: if currentNum not in self.unique:
self.unique.append(currentNum) self.unique.append(currentNum)
#Stop the timer #Stop the timer
self.timer.stop() self.timer.stop()
@@ -66,47 +67,39 @@ class Problem29(Problem):
self.solved = True self.solved = True
#Reset the problem so it can be run again #Reset the problem so it can be run again
def reset(self): def reset(self) -> None:
super().reset() super().reset()
self.unique.clear() self.unique.clear()
#Gets #Gets
#Returns the result of solving the problem #Returns the result of solving the problem
def getResult(self): def getResult(self) -> str:
#If the problem hasn't been solved throw an exception self.solvedCheck("result")
if(not self.solved):
raise Unsolved("You must solve the problem before you can see the result")
return f"The number of unique values generated by a^b for {self.__bottomA} <= a < = {self.__topA} and {self.__bottomB} <= b <= {self.__topB} is {len(self.unique)}" return f"The number of unique values generated by a^b for {self.__bottomA} <= a < = {self.__topA} and {self.__bottomB} <= b <= {self.__topB} is {len(self.unique)}"
#Returns the lowest possible value for a #Returns the lowest possible value for a
def getBottomA(self): def getBottomA(self) -> int:
#If the problem hasn't been solved throw an exception self.solvedCheck("lowest a")
if(not self.solved):
raise Unsolved("You must solve the problem before can you see the lowest possible A")
return self.__bottomA return self.__bottomA
#Returns the lowest possible value for a #Returns the lowest possible value for a
def getTopA(self): def getTopA(self) -> int:
#If the problem hasn't been solved throw an exception self.solvedCheck("highest a")
if(not self.solved):
raise Unsolved("You must solve the problem before can you see the highest possible A")
return self.__topA return self.__topA
#Returns the lowest possible value for a #Returns the lowest possible value for a
def getBottomB(self): def getBottomB(self) -> int:
#If the problem hasn't been solved throw an exception self.solvedCheck("lowest b")
if(not self.solved):
raise Unsolved("You must solve the problem before can you see the lowest possible B")
return self.__bottomB return self.__bottomB
#Returns the lowest possible value for a #Returns the lowest possible value for a
def getTopB(self): def getTopB(self) -> int:
#If the problem hasn't been solved throw an exception self.solvedCheck("highest b")
if(not self.solved):
raise Unsolved("You must solve the problem before can you see the highest possible B")
return self.__topB return self.__topB
#Returns a list of all unique values for a^b #Returns a list of all unique values for a^b
def getUnique(self) -> list: def getUnique(self) -> list:
#If the problem hasn't been solved throw an exception self.solvedCheck("unique values for a^b")
if(not self.solved):
raise Unsolved("You must solve the problem before can you see list of unique values")
return self.unique return self.unique
#Returns the number of unique values for a^b
def getNumUnique(self) -> int:
self.solvedCheck("number of unique values for a^b")
return len(self.unique)
""" Results: """ Results:

View File

@@ -1,11 +1,11 @@
#ProjectEuler/Python/Problem3.py #ProjectEuler/Python/Problem3.py
#Matthew Ellison #Matthew Ellison
# Created: 01-27-19 # Created: 01-27-19
#Modified: 10-30-20 #Modified: 07-24-21
#The largest prime factor of 600851475143 #The largest prime factor of 600851475143
#Unless otherwise listed, all of my non-standard imports can be gotten from my pyClasses repository at https://bitbucket.org/Mattrixwv/pyClasses #Unless otherwise listed, all of my non-standard imports can be gotten from my pyClasses repository at https://bitbucket.org/Mattrixwv/pyClasses
""" """
Copyright (C) 2020 Matthew Ellison Copyright (C) 2021 Matthew Ellison
This program is free software: you can redistribute it and/or modify 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 it under the terms of the GNU Lesser General Public License as published by
@@ -23,8 +23,7 @@
from Problems.Problem import Problem from Problems.Problem import Problem
from Algorithms import getFactors import NumberAlgorithms
from Unsolved import Unsolved
class Problem3(Problem): class Problem3(Problem):
@@ -33,13 +32,13 @@ class Problem3(Problem):
#Functions #Functions
#Constructor #Constructor
def __init__(self): def __init__(self) -> None:
super().__init__("What is the largest prime factor of 600851475143?") super().__init__("What is the largest prime factor of 600851475143?")
self.factors = [] self.factors = []
#Operational functions #Operational functions
#Solve the problem #Solve the problem
def solve(self): def solve(self) -> None:
#If the problem has already been solved do nothing and end the function #If the problem has already been solved do nothing and end the function
if(self.solved): if(self.solved):
return return
@@ -47,10 +46,12 @@ class Problem3(Problem):
#Start the timer #Start the timer
self.timer.start() self.timer.start()
#Get the factors of the number #Get the factors of the number
self.factors = getFactors(self.__goalNumber) self.factors = NumberAlgorithms.getFactors(self.__goalNumber)
#The last element should be the largest factor #The last element should be the largest factor
#Stop the timer #Stop the timer
self.timer.stop() self.timer.stop()
@@ -58,32 +59,23 @@ class Problem3(Problem):
self.solved = True self.solved = True
#Reset the problem so it can be run again #Reset the problem so it can be run again
def reset(self): def reset(self) -> None:
super().reset() super().reset()
self.factors.clear() self.factors.clear()
#Gets #Gets
#Returns the result of solving the problem #Returns the result of solving the problem
def getResult(self): def getResult(self) -> str:
#If the problem hasn't been solved throw an exception self.solvedCheck("result")
if(not self.solved):
raise Unsolved("You must solve the problem before you can see the result")
return f"The largest prime factor of {self.__goalNumber} is {self.factors[(len(self.factors) - 1)]}" return f"The largest prime factor of {self.__goalNumber} is {self.factors[(len(self.factors) - 1)]}"
#Returns the list of factors of the number #Returns the list of factors of the number
def getFactors(self) -> list: def getFactors(self) -> list:
#If the problem hasn't been solved throw an exceptions self.solvedCheck("factors")
if(not self.solved):
raise Unsolved("You must solve the problem before you can get the factors")
return self.factors return self.factors
#Returns the largest factor of the number #Returns the largest factor of the number
def getLargestFactor(self) -> int: def getLargestFactor(self) -> int:
#If the problem hasn't been solved throw an exceptions self.solvedCheck("largest factor")
if(not self.solved):
raise Unsolved("You must solve the problem before you can get the largest factor")
return self.factors[(len(self.factors) - 1)] return self.factors[(len(self.factors) - 1)]
#Returns the number for which we are getting the factor
def getGoalNumber(self) -> int:
return self.__goalNumber
"""Results: """Results:

View File

@@ -1,11 +1,11 @@
#ProjectEuler/Python/Problem30.py #ProjectEuler/Python/Problem30.py
#Matthew Ellison #Matthew Ellison
# Created: 10-28-19 # Created: 10-28-19
#Modified: 10-30-20 #Modified: 07-24-21
#Find the sum of all the numbers that can be written as the sum of the fifth powers of their digits. #Find the sum of all the numbers that can be written as the sum of the fifth powers of their digits.
#Unless otherwise listed, all of my non-standard imports can be gotten from my pyClasses repository at https://bitbucket.org/Mattrixwv/pyClasses #Unless otherwise listed, all of my non-standard imports can be gotten from my pyClasses repository at https://bitbucket.org/Mattrixwv/pyClasses
""" """
Copyright (C) 2020 Matthew Ellison Copyright (C) 2021 Matthew Ellison
This program is free software: you can redistribute it and/or modify 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 it under the terms of the GNU Lesser General Public License as published by
@@ -23,7 +23,6 @@
from Problems.Problem import Problem from Problems.Problem import Problem
from Unsolved import Unsolved
class Problem30(Problem): class Problem30(Problem):
@@ -34,14 +33,14 @@ class Problem30(Problem):
#Functions #Functions
#Constructor #Constructor
def __init__(self): def __init__(self) -> None:
super().__init__("Find the sum of all the numbers that can be written as the sum of the fifth powers of their digits.") super().__init__("Find the sum of all the numbers that can be written as the sum of the fifth powers of their digits.")
self.sumOfFifthNumbers = [] #This is an ArrayList of the numbers that are the sum of the fifth power of their digits self.sumOfFifthNumbers = [] #This is an ArrayList of the numbers that are the sum of the fifth power of their digits
self.sum = 0 #This is the sum of the sumOfFifthNumbers list self.sum = 0 #This is the sum of the sumOfFifthNumbers list
#Operational function #Operational function
#Solve the problem #Solve the problem
def solve(self): def solve(self) -> None:
#If the problem has already been solved do nothing and end the function #If the problem has already been solved do nothing and end the function
if(self.solved): if(self.solved):
return return
@@ -49,6 +48,7 @@ class Problem30(Problem):
#Start the timer #Start the timer
self.timer.start() self.timer.start()
#Start with the lowest number and increment until you reach the largest number #Start with the lowest number and increment until you reach the largest number
for currentNum in range(self.__bottomNum, self.__topNum): for currentNum in range(self.__bottomNum, self.__topNum):
#Get the digits of the number #Get the digits of the number
@@ -62,6 +62,7 @@ class Problem30(Problem):
if(sumOfPowers == currentNum): if(sumOfPowers == currentNum):
self.sumOfFifthNumbers.append(currentNum) self.sumOfFifthNumbers.append(currentNum)
#Stop the timer #Stop the timer
self.timer.stop() self.timer.stop()
@@ -80,46 +81,29 @@ class Problem30(Problem):
return listOfDigits return listOfDigits
#Reset the problem so it can be run again #Reset the problem so it can be run again
def reset(self): def reset(self) -> None:
super().reset() super().reset()
self.sumOfFifthNumbers.clear() self.sumOfFifthNumbers.clear()
#Gets #Gets
#Returns the result of solving the problem #Returns the result of solving the problem
def getResult(self): def getResult(self) -> str:
#If the problem hasn't been solved throw an exception self.solvedCheck("result")
if(not self.solved):
raise Unsolved("You must solve the problem before you can see the result")
return f"The sum of all the numbers that can be written as the sum of the fifth powers of their digits is {sum(self.sumOfFifthNumbers)}" return f"The sum of all the numbers that can be written as the sum of the fifth powers of their digits is {sum(self.sumOfFifthNumbers)}"
#Returns the top number to be checked #Returns the top number to be checked
def getTopNum(self) -> int: def getTopNum(self) -> int:
#If the problem hasn't been solved throw an exception self.solvedCheck("largest number checked")
if(not self.solved):
raise Unsolved("You must solve the problem before can you see the top number")
return self.__topNum return self.__topNum
#Returns a copy of the vector holding all the number that are the sum of the fifth powers of their digits #Returns a copy of the vector holding all the number that are the sum of the fifth powers of their digits
def getListOfSumsOfFifths(self) -> list: def getListOfSumsOfFifths(self) -> list:
#If the problem hasn't been solved throw an exception self.solvedCheck("list of all numbers that are the sum of the 5th power of their digits")
if(not self.solved):
raise Unsolved("You must solve the problem before can you see the list")
return self.sumOfFifthNumbers return self.sumOfFifthNumbers
#Returns the sum of all entries in sumOfFifthNumbers #Returns the sum of all entries in sumOfFifthNumbers
def getSumOfList(self) -> int: def getSumOfList(self) -> int:
#If the problem hasn't been solved throw an exception self.solvedCheck("sum of all numbers that are the sum of the 5th power of their digits")
if(not self.solved):
raise Unsolved("You must solve the problem before can you see the sum of the list")
return sum(self.sumOfFifthNumbers) return sum(self.sumOfFifthNumbers)
#This calls the appropriate functions if the script is called stand alone
if __name__ == "__main__":
problem = Problem30()
print(problem.getDescription()) #Print the description
problem.solve() #Call the function that answers the problem
#Print the results
print(problem.getResult())
print("It took " + problem.getTime() + " to solve this algorithm")
""" Results: """ Results:
The sum of all the numbers that can be written as the sum of the fifth powers of their digits is 443839 The sum of all the numbers that can be written as the sum of the fifth powers of their digits is 443839
It took an average of 4.068 seconds to run this problem through 100 iterations It took an average of 4.068 seconds to run this problem through 100 iterations

View File

@@ -1,11 +1,11 @@
#ProjectEuler/Python/Problem31.py #ProjectEuler/Python/Problem31.py
#Matthew Ellison #Matthew Ellison
# Created: 06-19-20 # Created: 06-19-20
#Modified: 10-30-20 #Modified: 07-24-21
#How many different ways can £2 be made using any number of coins? #How many different ways can £2 be made using any number of coins?
#Unless otherwise listed, all of my non-standard imports can be gotten from my pyClasses repository at https://bitbucket.org/Mattrixwv/pyClasses #Unless otherwise listed, all of my non-standard imports can be gotten from my pyClasses repository at https://bitbucket.org/Mattrixwv/pyClasses
""" """
Copyright (C) 2020 Matthew Ellison Copyright (C) 2021 Matthew Ellison
This program is free software: you can redistribute it and/or modify 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 it under the terms of the GNU Lesser General Public License as published by
@@ -23,7 +23,6 @@
from Problems.Problem import Problem from Problems.Problem import Problem
from Unsolved import Unsolved
class Problem31(Problem): class Problem31(Problem):
@@ -32,13 +31,13 @@ class Problem31(Problem):
#Functions #Functions
#Constructor #Constructor
def __init__(self): def __init__(self) -> None:
super().__init__("How many different ways can 2 pounds be made using any number of coins?") super().__init__("How many different ways can 2 pounds be made using any number of coins?")
self.permutations = 0 self.permutations = 0
#Operational functions #Operational functions
#Solve the problem #Solve the problem
def solve(self): def solve(self) -> None:
#If the problem has already been solved do nothing and end the function #If the problem has already been solved do nothing and end the function
if(self.solved): if(self.solved):
return return
@@ -46,6 +45,7 @@ class Problem31(Problem):
#Start the timer #Start the timer
self.timer.start() self.timer.start()
#Start with 200p and remove the necessary coins with each loop #Start with 200p and remove the necessary coins with each loop
for pound2 in range(self.__desiredValue, -1, -200): for pound2 in range(self.__desiredValue, -1, -200):
for pound1 in range(pound2, -1, -100): for pound1 in range(pound2, -1, -100):
@@ -56,6 +56,7 @@ class Problem31(Problem):
for pence2 in range(pence5, -1, -2): for pence2 in range(pence5, -1, -2):
self.permutations += 1 self.permutations += 1
#Stop the timer #Stop the timer
self.timer.stop() self.timer.stop()
@@ -63,22 +64,18 @@ class Problem31(Problem):
self.solved = True self.solved = True
#Reset the problem so it can be run again #Reset the problem so it can be run again
def reset(self): def reset(self) -> None:
super().reset() super().reset()
self.permutations = 0 self.permutations = 0
#Gets #Gets
#Returns the result of solving the problem #Returns the result of solving the problem
def getResult(self): def getResult(self) -> str:
#If the problem hasn't been solved throw an exception self.solvedCheck("result")
if(not self.solved):
raise Unsolved("You must solve the problem before you can see the result")
return f"There are {self.permutations} ways to make 2 pounds with the given denominations of coins" return f"There are {self.permutations} ways to make 2 pounds with the given denominations of coins"
#Returns the number of correct permutations of the coins #Returns the number of correct permutations of the coins
def getPermutations(self) -> int: def getPermutations(self) -> int:
#If the problem hasn't been solved throw an exception self.solvedCheck("number of correct permutations of the coins")
if(not self.solved):
raise Unsolved("You must solve the problem before can you see the number of permutations")
return self.permutations return self.permutations

View File

@@ -1,11 +1,11 @@
#ProjectEuler/ProjectEulerPython/Problems/Problem32.py #ProjectEuler/ProjectEulerPython/Problems/Problem32.py
#Matthew Ellison #Matthew Ellison
# Created: 07-28-20 # Created: 07-28-20
#Modified: 10-30-20 #Modified: 07-24-21
#Find the sum of all products whose multiplicand/multiplier/product identity can be written as a 1 through 9 pandigital. #Find the sum of all products whose multiplicand/multiplier/product identity can be written as a 1 through 9 pandigital.
#Unless otherwise listed, all of my non-standard imports can be gotten from my pyClasses repository at https://bitbucket.org/Mattrixwv/pyClasses #Unless otherwise listed, all of my non-standard imports can be gotten from my pyClasses repository at https://bitbucket.org/Mattrixwv/pyClasses
""" """
Copyright (C) 2020 Matthew Ellison Copyright (C) 2021 Matthew Ellison
This program is free software: you can redistribute it and/or modify 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 it under the terms of the GNU Lesser General Public License as published by
@@ -23,24 +23,23 @@
from Problems.Problem import Problem from Problems.Problem import Problem
from Unsolved import Unsolved
class Problem32(Problem): class Problem32(Problem):
#Structures #Structures
class ProductSet: class ProductSet:
def __init__(self, multiplicand: int, multiplier: int): def __init__(self, multiplicand: int, multiplier: int) -> None:
self.multiplicand = multiplicand self.multiplicand = multiplicand
self.multiplier = multiplier self.multiplier = multiplier
def getProduct(self) -> int: def getProduct(self) -> int:
return (self.multiplicand * self.multiplier) return (self.multiplicand * self.multiplier)
def getNumString(self) -> str: def getNumString(self) -> str:
return (str(self.multiplicand) + str(self.multiplier) + str(self.getProduct())) return (str(self.multiplicand) + str(self.multiplier) + str(self.getProduct()))
def __str__(self): def __str__(self) -> str:
return (str(self.multiplicand) + " x " + str(self.multiplier) + " = " + str(self.getProduct())) return (str(self.multiplicand) + " x " + str(self.multiplier) + " = " + str(self.getProduct()))
def __repr__(self): def __repr__(self) -> str:
return self.__str__() return self.__str__()
def __eq__(self, secondSet): def __eq__(self, secondSet) -> bool:
return (self.getProduct() == secondSet.getProduct()) return (self.getProduct() == secondSet.getProduct())
#Variables #Variables
@@ -50,14 +49,14 @@ class Problem32(Problem):
#Functions #Functions
#Constructor #Constructor
def __init__(self): def __init__(self) -> None:
super().__init__("Find the sum of all products whose multiplicand/multiplier/product identity can be written as a 1 through 9 pandigital.") super().__init__("Find the sum of all products whose multiplicand/multiplier/product identity can be written as a 1 through 9 pandigital.")
self.listOfProducts = [] #The list of unique products that are 1-9 pandigital self.listOfProducts = [] #The list of unique products that are 1-9 pandigital
self.sumOfPandigitals = 0 #The sum of the products of the pandigital numbers self.sumOfPandigitals = 0 #The sum of the products of the pandigital numbers
#Operational functions #Operational functions
#Solve the problem #Solve the problem
def solve(self): def solve(self) -> None:
#If the problem has already been solved do nothing and end the function #If the problem has already been solved do nothing and end the function
if(self.solved): if(self.solved):
return return
@@ -65,6 +64,7 @@ class Problem32(Problem):
#Start the timer #Start the timer
self.timer.start() self.timer.start()
#Create the multiplicand and start working your way up #Create the multiplicand and start working your way up
for multiplicand in range(1, self.__topMultiplicand + 1): for multiplicand in range(1, self.__topMultiplicand + 1):
#Run through all possible multipliers #Run through all possible multipliers
@@ -82,6 +82,7 @@ class Problem32(Problem):
for prod in self.listOfProducts: for prod in self.listOfProducts:
self.sumOfPandigitals += prod.getProduct() self.sumOfPandigitals += prod.getProduct()
#Stop the timer #Stop the timer
self.timer.stop() self.timer.stop()
@@ -104,23 +105,19 @@ class Problem32(Problem):
return True return True
#Reset the problem so it can be run again #Reset the problem so it can be run again
def reset(self): def reset(self) -> None:
super().reset() super().reset()
self.listOfProducts.clear() self.listOfProducts.clear()
self.sumOfPandigitals = 0 self.sumOfPandigitals = 0
#Gets #Gets
#Returns the result of solving the problem #Returns the result of solving the problem
def getResult(self): def getResult(self) -> str:
#If the problem hasn't been solved throw an exception self.solvedCheck("result")
if(not self.solved):
raise Unsolved("You must solve the problem before you can see the result")
return f"There are {self.listOfProducts} unique 1-9 pandigitals\nThe sum of the products of these pandigitals is {self.sumOfPandigitals}" return f"There are {self.listOfProducts} unique 1-9 pandigitals\nThe sum of the products of these pandigitals is {self.sumOfPandigitals}"
#Returns the sum of the pandigitals #Returns the sum of the pandigitals
def getSumOfPandigitals(self): def getSumOfPandigitals(self) -> int:
#If the problem hasn't been solved throw an exception self.solvedCheck("sum of the pandigitals")
if(not self.solved):
raise Unsolved("You must solve the problem before can you see the sum of the pandigitals")
return self.sumOfPandigitals return self.sumOfPandigitals

View File

@@ -1,7 +1,7 @@
#ProjectEuler/Python/Problem33.py #ProjectEuler/Python/Problem33.py
#Matthew Ellison #Matthew Ellison
# Created: 02-07-21 # Created: 02-07-21
#Modified: 02-07-21 #Modified: 07-24-21
""" """
The fraction 49/98 is a curious fraction, as an inexperienced mathematician in attempting to simplify it may incorrectly believe that 49/98 = 4/8, which is correct, is obtained by cancelling the 9s The fraction 49/98 is a curious fraction, as an inexperienced mathematician in attempting to simplify it may incorrectly believe that 49/98 = 4/8, which is correct, is obtained by cancelling the 9s
We shall consider fractions like, 30/50 = 3/5, to be trivial examples We shall consider fractions like, 30/50 = 3/5, to be trivial examples
@@ -28,9 +28,7 @@ If the product of these four fractions is given in its lowest common terms, find
from Problems.Problem import Problem from Problems.Problem import Problem
from Unsolved import Unsolved import ArrayAlgorithms
import Algorithms
class Problem33(Problem): class Problem33(Problem):
@@ -47,12 +45,12 @@ class Problem33(Problem):
#Functions #Functions
#Constructor #Constructor
def __init__(self): def __init__(self) -> None:
super().__init__("If the product of these four fractions is given in its lowest common terms, find the value of the denominator") super().__init__("If the product of these four fractions is given in its lowest common terms, find the value of the denominator")
#Operational Functions #Operational Functions
#Solve the problem #Solve the problem
def solve(self): def solve(self) -> None:
#If the problem has already been solved do nothing and end the function #If the problem has already been solved do nothing and end the function
if(self.solved): if(self.solved):
return return
@@ -60,6 +58,7 @@ class Problem33(Problem):
#Start the timer #Start the timer
self.timer.start() self.timer.start()
#Search every possible numerator/denominator pair #Search every possible numerator/denominator pair
for denominator in range(self.__minDenominator, self.__maxDenominator + 1): for denominator in range(self.__minDenominator, self.__maxDenominator + 1):
for numerator in range(self.__minNumerator, denominator): for numerator in range(self.__minNumerator, denominator):
@@ -93,13 +92,14 @@ class Problem33(Problem):
self.__denominators.append(denominator) self.__denominators.append(denominator)
#Get the product of the numbers #Get the product of the numbers
numProd = Algorithms.prod(self.__numerators) numProd = ArrayAlgorithms.prod(self.__numerators)
denomProd = Algorithms.prod(self.__denominators) denomProd = ArrayAlgorithms.prod(self.__denominators)
#Get the gcd to reduce to lowest terms #Get the gcd to reduce to lowest terms
gcd = Algorithms.gcd(numProd, denomProd) gcd = ArrayAlgorithms.gcd(numProd, denomProd)
#Save the denominator #Save the denominator
self.prodDenominator = int(denomProd / gcd) self.prodDenominator = int(denomProd / gcd)
#Stop the timer #Stop the timer
self.timer.stop() self.timer.stop()
@@ -107,40 +107,33 @@ class Problem33(Problem):
self.solved = True self.solved = True
#Reset the problem so it can be run again #Reset the problem so it can be run again
def reset(self): def reset(self) -> None:
super().reset() super().reset()
self.__numerators.clear() self.__numerators.clear()
self.__denominators.clear() self.__denominators.clear()
#Gets #Gets
#Returns the result of solving the problem #Returns the result of solving the problem
def getResult(self): def getResult(self) -> str:
#If the problem hasn't been solved throw an exception self.solvedCheck("result")
if(not self.solved):
raise Unsolved("You must solve the problem before you can see the result")
return f"The denominator of the product is {self.prodDenominator}" return f"The denominator of the product is {self.prodDenominator}"
#Returns the list of numerators #Returns the list of numerators
def getNumerators(self): def getNumerators(self) -> list:
#If the problem hasn't been solved throw an exception self.solvedCheck("list of numerators")
if(not self.solved):
raise Unsolved("You must solve the problem before you can see the numerators")
return self.__numerators return self.__numerators
#Returns the list of denominators #Returns the list of denominators
def getDenominators(self): def getDenominators(self) -> list:
#If the problem hasn't been solved throw an exception self.solvedCheck("list of denominators")
if(not self.solved):
raise Unsolved("You must solve the problem before you can see the denominators")
return self.__denominator return self.__denominator
#Returns the answer to the question #Returns the answer to the question
def getProdDenominator(self): def getProdDenominator(self) -> int:
#If the problem hasn't been solved throw an exception self.solvedCheck("denominator")
if(not self.solved):
raise Unsolved("You must solve the problem before you can see the answer")
return self.prodDenominator return self.prodDenominator
"""Results: """Results:
The denominator of the product is 100 The denominator of the product is 100
It took an average of 5.130 milliseconds to run this problem through 100 iterations It took an average of 5.130 milliseconds to run this problem through 100 iterations

View File

@@ -1,7 +1,7 @@
#ProjectEuler/ProjectEulerPython/Problems/Problem34.py #ProjectEuler/ProjectEulerPython/Problems/Problem34.py
#Matthew Ellison #Matthew Ellison
# Created: 06-01-21 # Created: 06-01-21
#Modified: 06-01-21 #Modified: 07-21-21
#Find the sum of all numbers which are equal to the sum of the factorial of their digits #Find the sum of all numbers which are equal to the sum of the factorial of their digits
#Unless otherwise listed, all of my non-standard imports can be gotten from my pyClasses repository at https://bitbucket.org/Mattrixwv/pyClasses #Unless otherwise listed, all of my non-standard imports can be gotten from my pyClasses repository at https://bitbucket.org/Mattrixwv/pyClasses
""" """
@@ -23,9 +23,7 @@
from Problems.Problem import Problem from Problems.Problem import Problem
from Unsolved import Unsolved import NumberAlgorithms
import Algorithms
class Problem34(Problem): class Problem34(Problem):
@@ -34,7 +32,7 @@ class Problem34(Problem):
#Functions #Functions
#Constructor #Constructor
def __init__(self): def __init__(self) -> None:
super().__init__("Find the sum of all numbers which are equal to the sum of the factorial of their digits") super().__init__("Find the sum of all numbers which are equal to the sum of the factorial of their digits")
self.totalSum = 0 self.totalSum = 0
self.factorials = [] self.factorials = []
@@ -43,7 +41,7 @@ class Problem34(Problem):
#Operational functions #Operational functions
#Solve the problem #Solve the problem
def solve(self): def solve(self) -> None:
#If the problem has already been solved do nothing and end the function #If the problem has already been solved do nothing and end the function
if(self.solved): if(self.solved):
return return
@@ -51,9 +49,10 @@ class Problem34(Problem):
#Start the timer #Start the timer
self.timer.start() self.timer.start()
#Pre-compute the possible factorials from 0! to 9! #Pre-compute the possible factorials from 0! to 9!
for cnt in range(0, 10): for cnt in range(0, 10):
self.factorials[cnt] = Algorithms.factorial(cnt) self.factorials[cnt] = NumberAlgorithms.factorial(cnt)
#Run through all possible numbers from 3-MAX_NUM and see if they equal the sum of their digit's factorials #Run through all possible numbers from 3-MAX_NUM and see if they equal the sum of their digit's factorials
for cnt in range(3, self.__max_num + 1): for cnt in range(3, self.__max_num + 1):
numString = str(cnt) numString = str(cnt)
@@ -64,6 +63,7 @@ class Problem34(Problem):
if(currentSum == cnt): if(currentSum == cnt):
self.totalSum += currentSum self.totalSum += currentSum
#Stop the timer #Stop the timer
self.timer.stop() self.timer.stop()
@@ -71,7 +71,7 @@ class Problem34(Problem):
self.solved = True self.solved = True
#Reset the problem so it can be run again #Reset the problem so it can be run again
def reset(self): def reset(self) -> None:
super().reset() super().reset()
self.totalSum = 0 self.totalSum = 0
self.factorials = [] self.factorials = []
@@ -80,24 +80,19 @@ class Problem34(Problem):
#Gets #Gets
#Returns the result of solving the problem #Returns the result of solving the problem
def getResult(self): def getResult(self) -> str:
#If the problem hasn't been solved throw an exception self.solvedCheck("result")
if(not self.solved):
raise Unsolved("You must solve the problem before you can see the result")
return f"The sum of all numbers that are the sum of their digit's factorials is {self.totalSum}" return f"The sum of all numbers that are the sum of their digit's factorials is {self.totalSum}"
#Returns the list of factorials from 0-9 #Returns the list of factorials from 0-9
def getFactorials(self): def getFactorials(self) -> list:
#If the problem hasn't been solved throw an exception self.solvedCheck("list of factorials")
if(not self.solved):
raise Unsolved("You must solve the problem before you can see the result")
return self.factorials return self.factorials
#Returns the sum of all numbers equal to the sum of their digit's factorials #Returns the sum of all numbers equal to the sum of their digit's factorials
def getSum(self): def getSum(self) -> int:
#If the problem hasn't been solved throw an exception self.solvedCheck("sum")
if(not self.solved):
raise Unsolved("You must solve the problem before you can see the result")
return self.totalSum return self.totalSum
""" Results: """ Results:
The sum of all numbers that are the sum of their digit's factorials is 40730 The sum of all numbers that are the sum of their digit's factorials is 40730
It took an average of 2.337 seconds to run this problem through 100 iterations It took an average of 2.337 seconds to run this problem through 100 iterations

View File

@@ -23,9 +23,7 @@
from Problems.Problem import Problem from Problems.Problem import Problem
from Unsolved import Unsolved import NumberAlgorithms
import Algorithms
class Problem35(Problem): class Problem35(Problem):
@@ -34,7 +32,7 @@ class Problem35(Problem):
#Functions #Functions
#Constructor #Constructor
def __init__(self): def __init__(self) -> None:
super().__init__("Find the sum of all numbers which are equal to the sum of the factorial of their digits") super().__init__("Find the sum of all numbers which are equal to the sum of the factorial of their digits")
self.primes = [] self.primes = []
self.circularPrimes = [] self.circularPrimes = []
@@ -50,7 +48,7 @@ class Problem35(Problem):
#Operational functions #Operational functions
#Solve the problem #Solve the problem
def solve(self): def solve(self) -> None:
#If the problem has already been solved do nothing and end the function #If the problem has already been solved do nothing and end the function
if(self.solved): if(self.solved):
return return
@@ -58,8 +56,9 @@ class Problem35(Problem):
#Start the timer #Start the timer
self.timer.start() self.timer.start()
#Get all primes under 1,000,000 #Get all primes under 1,000,000
self.primes = Algorithms.getPrimes(self.__max_num) self.primes = NumberAlgorithms.getPrimes(self.__max_num)
#Go through all primes, get all their rotations, and check if those numbers are also primes #Go through all primes, get all their rotations, and check if those numbers are also primes
for prime in self.primes: for prime in self.primes:
allRotationsPrime = True allRotationsPrime = True
@@ -74,6 +73,7 @@ class Problem35(Problem):
if(allRotationsPrime): if(allRotationsPrime):
self.circularPrimes.append(prime) self.circularPrimes.append(prime)
#Stop the timer #Stop the timer
self.timer.stop() self.timer.stop()
@@ -81,7 +81,7 @@ class Problem35(Problem):
self.solved = True self.solved = True
#Reset the problem so it can be run again #Reset the problem so it can be run again
def reset(self): def reset(self) -> None:
super().reset() super().reset()
self.primes = [] self.primes = []
self.circularPrimes = [] self.circularPrimes = []
@@ -89,27 +89,19 @@ class Problem35(Problem):
#Gets #Gets
#Returns a string with the solution to the problem #Returns a string with the solution to the problem
def getResult(self) -> str: def getResult(self) -> str:
#If the problem hasn't been solved throw an exception self.solvedCheck("result")
if(not self.solved):
raise Unsolved("You must solve the problem before you can see the result")
return f"The number of all circular prime numbers under {self.__max_num} is {len(self.circularPrimes)}" return f"The number of all circular prime numbers under {self.__max_num} is {len(self.circularPrimes)}"
#Returns the list of primes < max_num #Returns the list of primes < max_num
def getPrimes(self) -> list: def getPrimes(self) -> list:
#If the problem hasn't been solved throw an exception self.solvedCheck("list of primes")
if(not self.solved):
raise Unsolved("You must solve the porblem before you can see the primes")
return self.primes return self.primes
#Returns the list of circular primes < max_num #Returns the list of circular primes < max_num
def getCircularPrimes(self) -> list: def getCircularPrimes(self) -> list:
#If the problem hasn't been solved throw an exception self.solvedCheck("list of circular primes")
if(not self.solved):
raise Unsolved("You must solve the porblem before you can see the circular primes")
return self.circularPrimes return self.circularPrimes
#Returns the number of circular primes #Returns the number of circular primes
def getNumCircularPrimes(self) -> list: def getNumCircularPrimes(self) -> list:
#If the problem hasn't been solved throw an exception self.solvedCheck("number of circular primes")
if(not self.solved):
raise Unsolved("You must solve the porblem before you can see the number of circular primes")
return len(self.circularPrimes) return len(self.circularPrimes)

View File

@@ -1,7 +1,7 @@
#ProjectEuler/ProjectEulerPython/Problems/Problem36.py #ProjectEuler/ProjectEulerPython/Problems/Problem36.py
#Matthew Ellison #Matthew Ellison
# Created: 06-29-21 # Created: 06-29-21
#Modified: 06-29-21 #Modified: 07-24-21
#Find the sum of all numbers, less than one million, which are palindromic in base 10 and base 2. #Find the sum of all numbers, less than one million, which are palindromic in base 10 and base 2.
#Unless otherwise listed, all of my non-standard imports can be gotten from my pyClasses repository at https://bitbucket.org/Mattrixwv/pyClasses #Unless otherwise listed, all of my non-standard imports can be gotten from my pyClasses repository at https://bitbucket.org/Mattrixwv/pyClasses
""" """
@@ -23,9 +23,8 @@
from Problems.Problem import Problem from Problems.Problem import Problem
from Unsolved import Unsolved import NumberAlgorithms
import StringAlgorithms
import Algorithms
class Problem36(Problem): class Problem36(Problem):
@@ -34,14 +33,14 @@ class Problem36(Problem):
#Functions #Functions
#Constructor #Constructor
def __init__(self): def __init__(self) -> None:
super().__init__("Find the sum of all numbers, less than one million, which are palindromic in base 10 and base 2.") super().__init__("Find the sum of all numbers, less than one million, which are palindromic in base 10 and base 2.")
self.palindromes = [] self.palindromes = []
self.sumOfPal = 0 self.sumOfPal = 0
#Operational functions #Operational functions
#Solve the problem #Solve the problem
def solve(self): def solve(self) -> None:
#If the problem has already been solved do nothing and end the function #If the problem has already been solved do nothing and end the function
if(self.solved): if(self.solved):
return return
@@ -49,18 +48,20 @@ class Problem36(Problem):
#Start the timer #Start the timer
self.timer.start() self.timer.start()
#Start with 1, check if it is a palindrome in base 10 and 2, and continue to __max_num #Start with 1, check if it is a palindrome in base 10 and 2, and continue to __max_num
for num in range(1, self.__max_num + 1): for num in range(1, self.__max_num + 1):
#Check if num is a palindrome #Check if num is a palindrome
if(Algorithms.isPalindrome(str(num))): if(StringAlgorithms.isPalindrome(str(num))):
#Convert num to base 2 and see if that is a palindrome #Convert num to base 2 and see if that is a palindrome
binNum = Algorithms.toBin(num) binNum = NumberAlgorithms.toBin(num)
if(Algorithms.isPalindrome(binNum)): if(StringAlgorithms.isPalindrome(binNum)):
#Add num to the list of palindromes #Add num to the list of palindromes
self.palindromes.append(num) self.palindromes.append(num)
#Get the sum of all palindromes in the list #Get the sum of all palindromes in the list
self.sumOfPal = sum(self.palindromes) self.sumOfPal = sum(self.palindromes)
#Stop the timer #Stop the timer
self.timer.stop() self.timer.stop()
@@ -68,7 +69,7 @@ class Problem36(Problem):
self.solved = True self.solved = True
#Reset the problem so it can be run again #Reset the problem so it can be run again
def reset(self): def reset(self) -> None:
super().reset() super().reset()
self.palindromes = [] self.palindromes = []
self.sum = 0 self.sum = 0
@@ -76,23 +77,18 @@ class Problem36(Problem):
#Gets #Gets
#Returns a string with the solution to the problem #Returns a string with the solution to the problem
def getResult(self) -> str: def getResult(self) -> str:
#If the problem hasn't been solved throw an exception self.solvedCheck("result")
if(not self.solved):
raise Unsolved("You must solve the problem before you can see the result")
return f"The sum of all base 10 and base 2 palindromic numbers < {self.__max_num} is {self.sumOfPal}" return f"The sum of all base 10 and base 2 palindromic numbers < {self.__max_num} is {self.sumOfPal}"
#Return the list of palindromes < MAX_NUM #Return the list of palindromes < MAX_NUM
def getPalindromes(self) -> list: def getPalindromes(self) -> list:
#If the problem hasn't been solved throw an exception self.solvedCheck("list of palindromes")
if(not self.solved):
raise Unsolved("You must solve the problem before you can see the palindromes")
return self.palindromes return self.palindromes
#Return the sum of all elements in the list of palindromes #Return the sum of all elements in the list of palindromes
def getSumOfPalindromes(self) -> int: def getSumOfPalindromes(self) -> int:
#If the problem hasn't been solved throw an exception self.solvedCheck("sum of all palindromes")
if(not self.solved):
raise Unsolved("You must solve the problem before you can see the sum of the palindromes")
return self.sumOfPal return self.sumOfPal
""" Results: """ Results:
The sum of all base 10 and base 2 palindromic numbers < 999999 is 872187 The sum of all base 10 and base 2 palindromic numbers < 999999 is 872187
It took an average of 295.861 milliseconds to run this problem through 100 iterations It took an average of 295.861 milliseconds to run this problem through 100 iterations

View File

@@ -23,9 +23,7 @@
from Problems.Problem import Problem from Problems.Problem import Problem
from Unsolved import Unsolved import NumberAlgorithms
import Algorithms
class Problem37(Problem): class Problem37(Problem):
@@ -34,14 +32,14 @@ class Problem37(Problem):
#Functions #Functions
#Constructor #Constructor
def __init__(self): def __init__(self) -> None:
super().__init__("Find the sum of the only eleven primes that are both truncatable from left to right and right to left (2, 3, 5, and 7 are not counted).") super().__init__("Find the sum of the only eleven primes that are both truncatable from left to right and right to left (2, 3, 5, and 7 are not counted).")
self.truncPrimes = [] #All numbers that are truncatable primes self.truncPrimes = [] #All numbers that are truncatable primes
self.sumOfTruncPrimes = 0 #The sum of all elements in truncPrimes self.sumOfTruncPrimes = 0 #The sum of all elements in truncPrimes
#Operational functions #Operational functions
#Solve the problem #Solve the problem
def solve(self): def solve(self) -> None:
#If the problem has already been solved do nothing and end the function #If the problem has already been solved do nothing and end the function
if(self.solved): if(self.solved):
return return
@@ -49,8 +47,9 @@ class Problem37(Problem):
#Start the timer #Start the timer
self.timer.start() self.timer.start()
#Create the sieve and get the first prime number #Create the sieve and get the first prime number
sieve = Algorithms.primeGenerator() sieve = NumberAlgorithms.primeGenerator()
currentPrime = next(sieve) currentPrime = next(sieve)
#Loop through the sieve until you get to __last_prime_before_check #Loop through the sieve until you get to __last_prime_before_check
while(currentPrime < self.__last_prime_before_check): while(currentPrime < self.__last_prime_before_check):
@@ -77,7 +76,7 @@ class Problem37(Problem):
primeSubstring = primeString[truncLoc::] primeSubstring = primeString[truncLoc::]
#Convert the string to an int and see if the number is still prime #Convert the string to an int and see if the number is still prime
newPrime = int(primeSubstring) newPrime = int(primeSubstring)
if(not Algorithms.isPrime(newPrime)): if(not NumberAlgorithms.isPrime(newPrime)):
isTruncPrime = False isTruncPrime = False
break break
#Start removing digits from the right and see if the number stays prime #Start removing digits from the right and see if the number stays prime
@@ -87,7 +86,7 @@ class Problem37(Problem):
primeSubstring = primeString[0:len(primeString) - truncLoc] primeSubstring = primeString[0:len(primeString) - truncLoc]
#Convert the string to an int and see if the number is still prime #Convert the string to an int and see if the number is still prime
newPrime = int(primeSubstring) newPrime = int(primeSubstring)
if(not Algorithms.isPrime(newPrime)): if(not NumberAlgorithms.isPrime(newPrime)):
isTruncPrime = False isTruncPrime = False
break break
#If the number remained prime through all operations add it to the vector #If the number remained prime through all operations add it to the vector
@@ -99,6 +98,7 @@ class Problem37(Problem):
#Get the sum of all elements in the truncPrimes vector #Get the sum of all elements in the truncPrimes vector
self.sumOfTruncPrimes = sum(self.truncPrimes) self.sumOfTruncPrimes = sum(self.truncPrimes)
#Stop the timer #Stop the timer
self.timer.stop() self.timer.stop()
@@ -106,7 +106,7 @@ class Problem37(Problem):
self.solved = True self.solved = True
#Reset the problem so it can be run again #Reset the problem so it can be run again
def reset(self): def reset(self) -> None:
super().reset() super().reset()
self.truncPrimes = [] self.truncPrimes = []
self.sumOfTruncPrimes = 0 self.sumOfTruncPrimes = 0
@@ -114,23 +114,18 @@ class Problem37(Problem):
#Gets #Gets
#Returns a string with the solution to the problem #Returns a string with the solution to the problem
def getResult(self) -> str: def getResult(self) -> str:
#If the problem hasn't been solved throw an exception self.solvedCheck("result")
if(not self.solved):
raise Unsolved("You must solve the porblem before you can see the result")
return f"The sum of all left and right truncatable primes is {self.sumOfTruncPrimes}" return f"The sum of all left and right truncatable primes is {self.sumOfTruncPrimes}"
#Returns the list of primes that can be truncated #Returns the list of primes that can be truncated
def getTruncatablePrimes(self) -> list: def getTruncatablePrimes(self) -> list:
#If the problem hasn't been solved throw an exception self.solvedCheck("list of truncatable primes")
if(not self.solved):
raise Unsolved("You must solve the porblem before you can see the truncatable primes")
return self.truncPrimes return self.truncPrimes
#Returns the sum of all elements in truncPrimes #Returns the sum of all elements in truncPrimes
def getSumOfPrimes(self) -> int: def getSumOfPrimes(self) -> int:
#If the problem hasn't been solved throw an exception self.solvedCheck("sum of truncatable primes")
if(not self.solved):
raise Unsolved("You must solve the porblem before you can see the sum of the truncatable primes")
return self.sumOfTruncPrimes return self.sumOfTruncPrimes
""" Results: """ Results:
The sum of all left and right truncatable primes is 748317 The sum of all left and right truncatable primes is 748317
It took an average of 224.657 milliseconds to run this problem through 100 iterations It took an average of 224.657 milliseconds to run this problem through 100 iterations

View File

@@ -1,11 +1,11 @@
#ProjectEuler/Python/Problem4.py #ProjectEuler/Python/Problem4.py
#Matthew Ellison #Matthew Ellison
# Created: 01-28-19 # Created: 01-28-19
#Modified: 10-30-20 #Modified: 07-24-21
#Find the largest palindrome made from the product of two 3-digit numbers #Find the largest palindrome made from the product of two 3-digit numbers
#Unless otherwise listed, all of my non-standard imports can be gotten from my pyClasses repository at https://bitbucket.org/Mattrixwv/pyClasses #Unless otherwise listed, all of my non-standard imports can be gotten from my pyClasses repository at https://bitbucket.org/Mattrixwv/pyClasses
""" """
Copyright (C) 2020 Matthew Ellison Copyright (C) 2021 Matthew Ellison
This program is free software: you can redistribute it and/or modify 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 it under the terms of the GNU Lesser General Public License as published by
@@ -23,7 +23,6 @@
from Problems.Problem import Problem from Problems.Problem import Problem
from Unsolved import Unsolved
class Problem4(Problem): class Problem4(Problem):
@@ -33,13 +32,13 @@ class Problem4(Problem):
#Functions #Functions
#Constructor #Constructor
def __init__(self): def __init__(self) -> None:
super().__init__("Find the largest palindrome made from the product of two 3-digit numbers") super().__init__("Find the largest palindrome made from the product of two 3-digit numbers")
self.palindromes = [] #Holds all of the palindromes self.palindromes = [] #Holds all of the palindromes
#Operational functions #Operational functions
#Solve the problem #Solve the problem
def solve(self): def solve(self) -> None:
#If the problem has already been solved do nothing and end the function #If the problem has already been solved do nothing and end the function
if(self.solved): if(self.solved):
return return
@@ -47,6 +46,7 @@ class Problem4(Problem):
#Start the timer #Start the timer
self.timer.start() self.timer.start()
#Loop through every number from __lowestNum to __highestNum twice and multiply every number together #Loop through every number from __lowestNum to __highestNum twice and multiply every number together
for firstNum in range(self.__lowestNum, self.__highestNum + 1): for firstNum in range(self.__lowestNum, self.__highestNum + 1):
for secondNum in range(firstNum, self.__highestNum + 1): #You can start at num1 because 100 * 101 == 101 * 100 for secondNum in range(firstNum, self.__highestNum + 1): #You can start at num1 because 100 * 101 == 101 * 100
@@ -61,6 +61,7 @@ class Problem4(Problem):
#Sort the palindromes so that the last element is the largest #Sort the palindromes so that the last element is the largest
self.palindromes.sort() self.palindromes.sort()
#Stop the timer #Stop the timer
self.timer.stop() self.timer.stop()
@@ -68,28 +69,22 @@ class Problem4(Problem):
self.solved = True self.solved = True
#Reset the problem so it can be run again #Reset the problem so it can be run again
def reset(self): def reset(self) -> None:
super().reset() super().reset()
self.palindromes.clear() self.palindromes.clear()
#Gets #Gets
#Returns the result of solving the problem #Returns the result of solving the problem
def getResult(self): def getResult(self) -> str:
#If the problem hasn't been solved throw an exception self.solvedCheck("result")
if(not self.solved):
raise Unsolved("You must solve the problem before you can see the result")
return f"The largest palindrome made from the product of two 3-digit numbers is {self.palindromes[len(self.palindromes) - 1]}" return f"The largest palindrome made from the product of two 3-digit numbers is {self.palindromes[len(self.palindromes) - 1]}"
#Returns the list of all palindromes #Returns the list of all palindromes
def getPalindromes(self) -> list: def getPalindromes(self) -> list:
#If the problem hasn't been solved throw an exceptions self.solvedCheck("palindromes")
if(not self.solved):
raise Unsolved("You must solve the problem before you can get the list of palindromes")
return self.palindromes return self.palindromes
#Returns the largest palindrome #Returns the largest palindrome
def getLargestPalindrome(self) -> int: def getLargestPalindrome(self) -> int:
#If the problem hasn't been solved throw an exceptions self.solvedCheck("largest palindrome")
if(not self.solved):
raise Unsolved("You must solve the problem before you can get the largest palindrome")
return self.palindromes[len(self.palindromes) - 1] return self.palindromes[len(self.palindromes) - 1]

View File

@@ -1,11 +1,11 @@
#ProjectEulter/Python/Project5.py #ProjectEulter/Python/Project5.py
#Matthew Ellison #Matthew Ellison
# Created: 01-28-19 # Created: 01-28-19
#Modified: 10-30-20 #Modified: 07-24-21
#What is the smallest positive number that is evenly divisible by all of the numbers from 1 to 20? #What is the smallest positive number that is evenly divisible by all of the numbers from 1 to 20?
#Unless otherwise listed, all of my non-standard imports can be gotten from my pyClasses repository at https://bitbucket.org/Mattrixwv/pyClasses #Unless otherwise listed, all of my non-standard imports can be gotten from my pyClasses repository at https://bitbucket.org/Mattrixwv/pyClasses
""" """
Copyright (C) 2020 Matthew Ellison Copyright (C) 2021 Matthew Ellison
This program is free software: it can redistribute it and/or modify This program is free software: it can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by it under the terms of the GNU Lesser General Public License as published by
@@ -23,7 +23,6 @@
from Problems.Problem import Problem from Problems.Problem import Problem
from Unsolved import Unsolved
class Problem5(Problem): class Problem5(Problem):
@@ -33,13 +32,13 @@ class Problem5(Problem):
#Functions #Functions
#Constructor #Constructor
def __init__(self): def __init__(self) -> None:
super().__init__("What is the smallest positive number that is evenly divisible by all of the numbers from 1 to 20?") super().__init__("What is the smallest positive number that is evenly divisible by all of the numbers from 1 to 20?")
self.smallestNum = 0 self.smallestNum = 0
#Operational functions #Operational functions
#Solve the problem #Solve the problem
def solve(self): def solve(self) -> None:
#If the problem has already been solved do nothing and end the function #If the problem has already been solved do nothing and end the function
if(self.solved): if(self.solved):
return return
@@ -47,6 +46,7 @@ class Problem5(Problem):
#Start the timer #Start the timer
self.timer.start() self.timer.start()
#Start at 20 and loop through all numbers until it find one that works #Start at 20 and loop through all numbers until it find one that works
#It must be at least 20 to be divisible by 20 #It must be at least 20 to be divisible by 20
numFound = False #A flag for finding the divisible number numFound = False #A flag for finding the divisible number
@@ -68,6 +68,7 @@ class Problem5(Problem):
#Set the smallest number to the number we just found #Set the smallest number to the number we just found
self.smallestNum = currentNum self.smallestNum = currentNum
#Stop the timer #Stop the timer
self.timer.stop() self.timer.stop()
@@ -75,22 +76,18 @@ class Problem5(Problem):
self.solved = True self.solved = True
#Reset the problem so it can be run again #Reset the problem so it can be run again
def reset(self): def reset(self) -> None:
super().reset() super().reset()
self.smallestNum = 0 self.smallestNum = 0
#Gets #Gets
#Returns the result of solving the problem #Returns the result of solving the problem
def getResult(self): def getResult(self) -> str:
#If the problem hasn't been solved throw an exception self.solvedCheck("result")
if(not self.solved):
raise Unsolved("You must solve the problem before you can see the result")
return f"The smallest positive number that is evenly divisible by all numbers 1-20 is {self.smallestNum}" return f"The smallest positive number that is evenly divisible by all numbers 1-20 is {self.smallestNum}"
#Returns the requested number #Returns the requested number
def getNumber(self) -> int: def getNumber(self) -> int:
#If the problem hasn't been solved throw an exceptions self.solvedCheck("number")
if(not self.solved):
raise Unsolved("You must solve the problem before you can get the requested number")
return self.smallestNum return self.smallestNum

View File

@@ -1,11 +1,11 @@
#ProjectEuler/Python/Problem6.py #ProjectEuler/Python/Problem6.py
#Matthew Ellison #Matthew Ellison
# Created: 01-28-19 # Created: 01-28-19
#Modified: 10-29-20 #Modified: 07-24-21
#Find the difference between the sum of the squares of the first one hundred natural numbers and the square of the sum #Find the difference between the sum of the squares of the first one hundred natural numbers and the square of the sum
#Unless otherwise listed, all of my non-standard imports can be gotten from my pyClasses repository at https://bitbucket.org/Mattrixwv/pyClasses #Unless otherwise listed, all of my non-standard imports can be gotten from my pyClasses repository at https://bitbucket.org/Mattrixwv/pyClasses
""" """
Copyright (C) 2020 Matthew Ellison Copyright (C) 2021 Matthew Ellison
This program is free software: you can redistribute it and/or modify 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 it under the terms of the GNU Lesser General Public License as published by
@@ -23,7 +23,6 @@
from Problems.Problem import Problem from Problems.Problem import Problem
from Unsolved import Unsolved
class Problem6(Problem): class Problem6(Problem):
@@ -33,14 +32,14 @@ class Problem6(Problem):
#Functions #Functions
#Constructor #Constructor
def __init__(self): def __init__(self) -> None:
super().__init__("Find the difference between the sum of the squares of the first one hundred natural numbers and the square of the sum.") super().__init__("Find the difference between the sum of the squares of the first one hundred natural numbers and the square of the sum.")
self.sumOfSquares = 0 #Holds the sum of the squares of all the numbers self.sumOfSquares = 0 #Holds the sum of the squares of all the numbers
self.squareOfSum = 0 #Holds the square of the sum of all the numbers self.squareOfSum = 0 #Holds the square of the sum of all the numbers
#Operational functions #Operational functions
#Solve the problem #Solve the problem
def solve(self): def solve(self) -> None:
#If the problem has already been solved do nothing and end the function #If the problem has already been solved do nothing and end the function
if(self.solved): if(self.solved):
return return
@@ -48,6 +47,7 @@ class Problem6(Problem):
#Start the timer #Start the timer
self.timer.start() self.timer.start()
#Run through all numbers from 1-100 and add them to the approriate sums #Run through all numbers from 1-100 and add them to the approriate sums
for num in range(self.__startNum, self.__endNum + 1): for num in range(self.__startNum, self.__endNum + 1):
self.sumOfSquares += (num * num) #Get the sum of the squares of the first 100 natural numbers self.sumOfSquares += (num * num) #Get the sum of the squares of the first 100 natural numbers
@@ -55,6 +55,7 @@ class Problem6(Problem):
#Square the normal sum #Square the normal sum
self.squareOfSum *= self.squareOfSum self.squareOfSum *= self.squareOfSum
#Stop the timer #Stop the timer
self.timer.stop() self.timer.stop()
@@ -62,35 +63,27 @@ class Problem6(Problem):
self.solved = True self.solved = True
#Reset the problem so it can be run again #Reset the problem so it can be run again
def reset(self): def reset(self) -> None:
super().reset() super().reset()
self.squareOfSum = 0 self.squareOfSum = 0
self.sumOfSquares = 0 self.sumOfSquares = 0
#Gets #Gets
#Returns the result of solving the problem #Returns the result of solving the problem
def getResult(self): def getResult(self) -> str:
#If the problem hasn't been solved throw an exception self.solvedCheck("result")
if(not self.solved):
raise Unsolved("You must solve the problem before you can see the result")
return f"The difference between the sum of the squares and the square of the sum of the numbers 1-100 is {abs(self.sumOfSquares - self.squareOfSum)}" return f"The difference between the sum of the squares and the square of the sum of the numbers 1-100 is {abs(self.sumOfSquares - self.squareOfSum)}"
#Returns the sum of all the squares #Returns the sum of all the squares
def getSumOfSquares(self) -> int: def getSumOfSquares(self) -> int:
#If the problem hasn't been solved throw an exceptions self.solvedCheck("sum of the squares")
if(not self.solved):
raise Unsolved("You must solve the problem before you can get the sum of squares")
return self.sumOfSquares return self.sumOfSquares
#Return the sqare of all of the sums #Return the sqare of all of the sums
def getSquareOfSum(self) -> int: def getSquareOfSum(self) -> int:
#If the problem hasn't been solved throw an exceptions self.solvedCheck("square of the sums")
if(not self.solved):
raise Unsolved("You must solve the problem before you can get the square of sum")
return self.squareOfSum return self.squareOfSum
#Returns the requested difference #Returns the requested difference
def getDifference(self) -> int: def getDifference(self) -> int:
#If the problem hasn't been solved throw an exceptions self.solvedCheck("difference between the two numbers")
if(not self.solved):
raise Unsolved("You must solve the problem before you can get the difference between the sum of squares and square of sum")
return abs(self.sumOfSquares - self.squareOfSum) return abs(self.sumOfSquares - self.squareOfSum)

View File

@@ -1,7 +1,7 @@
#ProjectEuler/Python/Problem67.py #ProjectEuler/Python/Problem67.py
#Matthew Ellison #Matthew Ellison
# Created: 03-26-19 # Created: 03-26-19
#Modified: 10-30-20 #Modified: 07-24-21
#Find the maximum total from top to bottom #Find the maximum total from top to bottom
""" """
59 59
@@ -107,7 +107,7 @@
""" """
#Unless otherwise listed, all of my non-standard imports can be gotten from my pyClasses repository at https://bitbucket.org/Mattrixwv/pyClasses #Unless otherwise listed, all of my non-standard imports can be gotten from my pyClasses repository at https://bitbucket.org/Mattrixwv/pyClasses
""" """
Copyright (C) 2020 Matthew Ellison Copyright (C) 2021 Matthew Ellison
This program is free software: you can redistribute it and/or modify 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 it under the terms of the GNU Lesser General Public License as published by
@@ -125,7 +125,6 @@
from Problems.Problem import Problem from Problems.Problem import Problem
from Unsolved import Unsolved
from collections import namedtuple from collections import namedtuple
@@ -238,7 +237,7 @@ class Problem67(Problem):
#Functions #Functions
#Constructor #Constructor
def __init__(self): def __init__(self) -> None:
super().__init__("Find the maximum total from top to bottom") super().__init__("Find the maximum total from top to bottom")
self.foundPoints = [] #For the points that I have already found the shortest distance to self.foundPoints = [] #For the points that I have already found the shortest distance to
self.possiblePoints = [] #For the locations you are checking this round self.possiblePoints = [] #For the locations you are checking this round
@@ -246,7 +245,7 @@ class Problem67(Problem):
#Operational functions #Operational functions
#Solve the problem #Solve the problem
def solve(self): def solve(self) -> None:
#If the problem has already been solved do nothing and end the function #If the problem has already been solved do nothing and end the function
if(self.solved): if(self.solved):
return return
@@ -254,6 +253,7 @@ class Problem67(Problem):
#Start the timer #Start the timer
self.timer.start() self.timer.start()
#Invert the list so that each element = 100 - element #Invert the list so that each element = 100 - element
self.invert() self.invert()
@@ -294,6 +294,7 @@ class Problem67(Problem):
#Invert the list so it can be read again #Invert the list so it can be read again
self.invert() self.invert()
#Stop the timer #Stop the timer
self.timer.stop() self.timer.stop()
@@ -301,13 +302,13 @@ class Problem67(Problem):
self.solved = True self.solved = True
#This function turns every number in the array into (100 - num) to allow you to find the largest numbers rather than the smallest #This function turns every number in the array into (100 - num) to allow you to find the largest numbers rather than the smallest
def invert(self): def invert(self) -> None:
for rowCnt in range(0, self.__numRows): for rowCnt in range(0, self.__numRows):
for colCnt in range(0, len(self.__listNum[rowCnt])): for colCnt in range(0, len(self.__listNum[rowCnt])):
self.__listNum[rowCnt][colCnt] = 100 - self.__listNum[rowCnt][colCnt] self.__listNum[rowCnt][colCnt] = 100 - self.__listNum[rowCnt][colCnt]
#This function removes every element in listNum that is equal to loc #This function removes every element in listNum that is equal to loc
def removeIf(self, listNum: list, loc: tuple): def removeIf(self, listNum: list, loc: tuple) -> None:
location = 0 location = 0
while(location < len(listNum)): while(location < len(listNum)):
if((listNum[location].xLocation == loc.xLocation) and (listNum[location].yLocation == loc.yLocation)): if((listNum[location].xLocation == loc.xLocation) and (listNum[location].yLocation == loc.yLocation)):
@@ -316,7 +317,7 @@ class Problem67(Problem):
location += 1 location += 1
#Reset the problem so it can be run again #Reset the problem so it can be run again
def reset(self): def reset(self) -> None:
super().reset() super().reset()
self.foundPoints.clear() self.foundPoints.clear()
self.possiblePoints.clear() self.possiblePoints.clear()
@@ -324,33 +325,27 @@ class Problem67(Problem):
#Gets #Gets
#Returns the result of solving the problem #Returns the result of solving the problem
def getResult(self): def getResult(self) -> str:
#If the problem hasn't been solved throw an exception self.solvedCheck("result")
if(not self.solved):
raise Unsolved("You must solve the problem before you can see the result")
return f"The value of the longest path is {self.actualTotal}" return f"The value of the longest path is {self.actualTotal}"
#Returns the pyramid that was traversed as a string #Returns the pyramid that was traversed as a string
def getPyramid(self) -> str: def getPyramid(self) -> str:
if(not self.solved): self.solvedCheck("pyramid of numbers")
raise Unsolved("You must solve the problem before you can get the pyramid") pyramidString = ""
results = ""
#Loop through all elements of the list and print them #Loop through all elements of the list and print them
for row in self.listNum: for row in self.listNum:
for column in row: for column in row:
results += "{:02d}".format(column) pyramidString += "{:02d}".format(column)
results += '\n' pyramidString += '\n'
return results return pyramidString
#Returns the trail the algorithm took as a string #Returns the trail the algorithm took as a string
def getTrail(self) -> str: def getTrail(self) -> str:
if(not self.solved): self.solvedCheck("trail of the shortest path")
raise Unsolved("You must solve the problem before you can get the trail")
#TODO: Implement this #TODO: Implement this
return "" return ""
#Returns the total that was asked for #Returns the total that was asked for
def getTotal(self) -> int: def getTotal(self) -> int:
if(not self.solved): self.solvedCheck("total")
raise Unsolved("You must solve the problem before you can get the total")
return self.actualTotal return self.actualTotal

View File

@@ -1,11 +1,11 @@
#Project Eulter/Python/Problem7.py #Project Eulter/Python/Problem7.py
#Matthew Ellison #Matthew Ellison
# Created: 01-29-19 # Created: 01-29-19
#Modified: 10-30-20 #Modified: 07-24-21
#What is the 10001st prime number? #What is the 10001st prime number?
#Unless otherwise listed, all of my non-standard imports can be gotten from my pyClasses repository at https://bitbucket.org/Mattrixwv/pyClasses #Unless otherwise listed, all of my non-standard imports can be gotten from my pyClasses repository at https://bitbucket.org/Mattrixwv/pyClasses
""" """
Copyright (C) 2020 Matthew Ellison Copyright (C) 2021 Matthew Ellison
This program is free software: you can redistribute it and/or modify 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 it under the terms of the GNU Lesser General Public License as published by
@@ -23,8 +23,7 @@
from Problems.Problem import Problem from Problems.Problem import Problem
from Unsolved import Unsolved import NumberAlgorithms
from Algorithms import getNumPrimes
class Problem7(Problem): class Problem7(Problem):
@@ -33,13 +32,13 @@ class Problem7(Problem):
#Functions #Functions
#Constructor #Constructor
def __init__(self): def __init__(self) -> None:
super().__init__("What is the 10001st prime number?") super().__init__("What is the 10001st prime number?")
self.primes = [] self.primes = []
#Operational functions #Operational functions
#Solve the problem #Solve the problem
def solve(self): def solve(self) -> None:
#If the problem has already been solved do nothing and end the function #If the problem has already been solved do nothing and end the function
if(self.solved): if(self.solved):
return return
@@ -47,8 +46,10 @@ class Problem7(Problem):
#Start the timer #Start the timer
self.timer.start() self.timer.start()
#Get the correct number of primes #Get the correct number of primes
self.primes = getNumPrimes(self.__numPrimes) self.primes = NumberAlgorithms.getNumPrimes(self.__numPrimes)
#Stop the timer #Stop the timer
self.timer.stop() self.timer.stop()
@@ -57,22 +58,18 @@ class Problem7(Problem):
self.solved = True self.solved = True
#Reset the problem so it can be run again #Reset the problem so it can be run again
def reset(self): def reset(self) -> None:
super().reset() super().reset()
self.primes.clear() self.primes.clear()
#Gets #Gets
#Returns the result of solving the problem #Returns the result of solving the problem
def getResult(self): def getResult(self) -> str:
#If the problem hasn't been solved throw an exception self.solvedCheck("result")
if(not self.solved):
raise Unsolved("You must solve the problem before you can see the result")
return f"The {self.__numPrimes}st prime number is {self.primes[self.__numPrimes - 1]}" return f"The {self.__numPrimes}st prime number is {self.primes[self.__numPrimes - 1]}"
#Returns the requested prime number #Returns the requested prime number
def getPrime(self) -> int: def getPrime(self) -> int:
#If the problem hasn't been solved throw an exception self.solvedCheck("prime")
if(not self.solved):
raise Unsolved("You must solve the problem before you can get the requested prime")
return self.primes[len(self.primes) - 1] return self.primes[len(self.primes) - 1]

View File

@@ -1,7 +1,7 @@
#Project Euler/Python/Problem8.py #Project Euler/Python/Problem8.py
#Matthew Ellison #Matthew Ellison
# Created: 01-29-19 # Created: 01-29-19
#Modified: 10-30-20 #Modified: 07-24-21
#Find the thirteen adjacent digits in the 1000-digit number that have the greatest product. What is the value of this product? #Find the thirteen adjacent digits in the 1000-digit number that have the greatest product. What is the value of this product?
""" """
73167176531330624919225119674426574742355349194934 73167176531330624919225119674426574742355349194934
@@ -27,7 +27,7 @@
""" """
#Unless otherwise listed, all of my non-standard imports can be gotten from my pyClasses repository at https://bitbucket.org/Mattrixwv/pyClasses #Unless otherwise listed, all of my non-standard imports can be gotten from my pyClasses repository at https://bitbucket.org/Mattrixwv/pyClasses
""" """
Copyright (C) 2020 Matthew Ellison Copyright (C) 2021 Matthew Ellison
This program is free software: you can redistribute it and/or modify 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 it under the terms of the GNU Lesser General Public License as published by
@@ -45,7 +45,6 @@
from Problems.Problem import Problem from Problems.Problem import Problem
from Unsolved import Unsolved
class Problem8(Problem): class Problem8(Problem):
@@ -55,14 +54,14 @@ class Problem8(Problem):
#Functions #Functions
#Constructor #Constructor
def __init__(self): def __init__(self) -> None:
super().__init__("Find the thirteen adjacent digits in the 1000-digit number that have the greatest product. What is the value of this product?") super().__init__("Find the thirteen adjacent digits in the 1000-digit number that have the greatest product. What is the value of this product?")
self.maxNums = "" #Holds the string of the largest product self.maxNums = "" #Holds the string of the largest product
self.maxProduct = 0 #Holds the largest product of 13 numbers self.maxProduct = 0 #Holds the largest product of 13 numbers
#Operational functions #Operational functions
#Solve the problem #Solve the problem
def solve(self): def solve(self) -> None:
#If the problem has already been solved do nothing and end the function #If the problem has already been solved do nothing and end the function
if(self.solved): if(self.solved):
return return
@@ -70,6 +69,7 @@ class Problem8(Problem):
#Start the timer #Start the timer
self.timer.start() self.timer.start()
#Start at the 13th entry and multiply all single digit numbers before and including that number together #Start at the 13th entry and multiply all single digit numbers before and including that number together
cnt = 12 #The location in the number that you are working from cnt = 12 #The location in the number that you are working from
for cnt in range(12, len(self.__number)): for cnt in range(12, len(self.__number)):
@@ -81,37 +81,32 @@ class Problem8(Problem):
#Move to the next location #Move to the next location
cnt += 1 cnt += 1
#Stop the timer #Stop the timer
self.timer.stop self.timer.stop()
#Throw a flag to show the problem is solved #Throw a flag to show the problem is solved
self.solved = True self.solved = True
#Reset the problem so it can be run again #Reset the problem so it can be run again
def reset(self): def reset(self) -> None:
super().reset() super().reset()
self.maxNums = "" self.maxNums = ""
self.maxProduct = 0 self.maxProduct = 0
#Gets #Gets
#Returns the result of solving the problem #Returns the result of solving the problem
def getResult(self): def getResult(self) -> str:
#If the problem hasn't been solved throw an exception self.solvedCheck("result")
if(not self.solved):
raise Unsolved("You must solve the problem before you can see the result")
return f"The largest product of 13 adjacent digits in the number is {self.maxProduct}\n" \ return f"The largest product of 13 adjacent digits in the number is {self.maxProduct}\n" \
f"The numbers are: {self.maxNums}" f"The numbers are: {self.maxNums}"
#Returns the string of number that produces the largest product #Returns the string of number that produces the largest product
def getLargestNums(self) -> str: def getLargestNums(self) -> str:
#If the problem hasn't been solved throw an exception self.solvedCheck("numbers that make the largest product")
if(not self.solved):
raise Unsolved("You must solve the problem before you can get the nums the produce the largest product")
return self.maxNums return self.maxNums
#Returns the requested product #Returns the requested product
def getLargestProduct(self) -> int: def getLargestProduct(self) -> int:
#If the problem hasn't been solved throw an exception self.solvedCheck("product of the numbers")
if(not self.solved):
raise Unsolved("You must solve the problem before you can get the requested product")
return self.maxProduct return self.maxProduct

View File

@@ -1,11 +1,11 @@
#Project Euler/Python/Problem9.py #Project Euler/Python/Problem9.py
#Matthew Ellison #Matthew Ellison
# Created: 01-29-19 # Created: 01-29-19
#Modified: 10-30-20 #Modified: 07-24-21
#There exists exactly one Pythagorean triplet for which a + b + c = 1000. Find the product abc. #There exists exactly one Pythagorean triplet for which a + b + c = 1000. Find the product abc.
#Unless otherwise listed, all of my non-standard imports can be gotten from my pyClasses repository at https://bitbucket.org/Mattrixwv/pyClasses #Unless otherwise listed, all of my non-standard imports can be gotten from my pyClasses repository at https://bitbucket.org/Mattrixwv/pyClasses
""" """
Copyright (C) 2020 Matthew Ellison Copyright (C) 2021 Matthew Ellison
This program is free software: you can redistribute it and/or modify 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 it under the terms of the GNU Lesser General Public License as published by
@@ -23,14 +23,13 @@
from Problems.Problem import Problem from Problems.Problem import Problem
from Unsolved import Unsolved
import math import math
class Problem9(Problem): class Problem9(Problem):
#Functions #Functions
#Constructor #Constructor
def __init__(self): def __init__(self) -> None:
super().__init__("There exists exactly one Pythagorean triplet for which a + b + c = 1000. Find the product abc.") super().__init__("There exists exactly one Pythagorean triplet for which a + b + c = 1000. Find the product abc.")
self.a = 1 self.a = 1
self.b = 0 self.b = 0
@@ -39,7 +38,7 @@ class Problem9(Problem):
#Operational functions #Operational functions
#Solve the problem #Solve the problem
def solve(self): def solve(self) -> None:
#If the problem has already been solved do nothing and end the function #If the problem has already been solved do nothing and end the function
if(self.solved): if(self.solved):
return return
@@ -47,6 +46,7 @@ class Problem9(Problem):
#Start the timer #Start the timer
self.timer.start() self.timer.start()
#Start with the lowest possible a , 1, and search for the b and c to complete the triplet #Start with the lowest possible a , 1, and search for the b and c to complete the triplet
while((self.a <= (1000 / 3)) and (not self.found)): while((self.a <= (1000 / 3)) and (not self.found)):
#Setup b and c #Setup b and c
@@ -66,6 +66,7 @@ class Problem9(Problem):
else: else:
self.a += 1 self.a += 1
#Stop the timer #Stop the timer
self.timer.stop() self.timer.stop()
@@ -73,7 +74,7 @@ class Problem9(Problem):
self.solved = True self.solved = True
#Reset the problem so it can be run again #Reset the problem so it can be run again
def reset(self): def reset(self) -> None:
super().reset() super().reset()
self.a = 1 self.a = 1
self.b = 0 self.b = 0
@@ -82,35 +83,25 @@ class Problem9(Problem):
#Gets #Gets
#Returns the result of solving the problem #Returns the result of solving the problem
def getResult(self): def getResult(self) -> str:
#If the problem hasn't been solved throw an exception self.solvedCheck("result")
if(not self.solved):
raise Unsolved("You must solve the problem before you can see the result")
return f"The Pythagorean triplet where a + b + c = 1000 is {self.a} {self.b} {int(self.c)}\n" \ return f"The Pythagorean triplet where a + b + c = 1000 is {self.a} {self.b} {int(self.c)}\n" \
f"The product of those numbers is {int(self.a * self.b * self.c)}" f"The product of those numbers is {int(self.a * self.b * self.c)}"
#Returns the length of the first side #Returns the length of the first side
def getSideA(self) -> int: def getSideA(self) -> int:
#If the problem hasn't been solved throw an exception self.solvedCheck("first side")
if(not self.solved):
raise Unsolved("You must solve the problem before you can get the length of the first side")
return self.a return self.a
#Returns the length of the second side #Returns the length of the second side
def getSideB(self) -> int: def getSideB(self) -> int:
#If the problem hasn't been solved throw an exception self.solvedCheck("second side")
if(not self.solved):
raise Unsolved("You must solve the problem before you can get the length of the second side")
return self.b return self.b
#Returns the length of the hyp #Returns the length of the hyp
def getSideC(self) -> float: def getSideC(self) -> float:
#If the problem hasn't been solved throw an exception self.solvedCheck("third side")
if(not self.solved):
raise Unsolved("You must solve the problem before you can get the length of the hyp")
return self.c return self.c
#Returns the product of the 3 sides #Returns the product of the 3 sides
def getProduct(self) -> int: def getProduct(self) -> int:
#If the problem hasn't been solved throw an exception self.solvedCheck("product of all three sides")
if(not self.solved):
raise Unsolved("You must solve the problem before you can get the length first side")
return int(self.a * self.b * self.c) return int(self.a * self.b * self.c)