#ProjectEuler/Python/Problem12.py #Matthew Ellison # Created: 01-31-19 #Modified: 03-28-19 #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 """ Copyright (C) 2019 Matthew Ellison This program is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program. If not, see . """ from Stopwatch import Stopwatch from Algorithms import getDivisors __goalDivisors = 500 #The number of divisors a number needs to reach def Problem12(): #Setup the variables triangularNumber = 1 #Holds the triangular numbers nextNumber = 2 #The next number to be added to the triangular number foundNumber = False #A flag for when the triangular number has over __goalDivisors divisors #Start at the first triangular number and loop around, moving to the next, until you find one with the appropriate number of divisors while((not foundNumber) and (triangularNumber > 0)): #Make sure you haven't caused an overflow and made trianularNumber negative #See how many divisors this triangular number has divisors = getDivisors(triangularNumber) #If it did have enough raise a flag to stop the loop if(len(divisors) > __goalDivisors): foundNumber = True else: triangularNumber += nextNumber #Add the next number to continue the triangular sequence nextNumber += 1 #Advance to the next number in the triangular sequence #Print the results if(triangularNumber <= 0): print("There was an error. Could not find a triangular number with " + str(__goalDivisors) + " divisors before overflow") else: print("The first triangular number with more than " + str(__goalDivisors) + " divisors is " + str(triangularNumber)) #If you are running this file, automatically start the correct function if __name__ == "__main__": timer = Stopwatch() #Determines the algorithm's run time timer.start() #Start the timer Problem12() #Call the function that answers the question timer.stop() #Stop the timer #Print the results of the timer print("It took " + timer.getString() + " to run this algorithm") """Results: The first triangular number with more than 500 divisors is 76576500 It took 2.898 seconds to run this algorithm """