The Home for People Who Like to Flip Out and Write Code
Project Euler: Problem 12
Problem 12 brings back an interesting mathematical concept:
triangular numbers. Triangular numbers (and
the formula for finding one) are the slightly more sophisticated
approach I mentioned in my writeup for Problem 6. Writing
a generator for triangular numbers is easy enough, as is writing some
logic to factorize (not prime factorize) a number. Given those two, the
solution is easy enough.
"""Solves Problem 12 of Project Euler."""importmathdeffactors(to_factor):"""Find the factors of to_factor."""factors=[]divisor=1while(divisor<=int(math.sqrt(to_factor))):ifnotto_factor%divisor:quotient=to_factor/divisorfactors.append(divisor)factors.append(quotient)divisor+=1returnfactorsdeftriangular_numbers():"""Generate the triangular numbers."""current=0position=1whileTrue:current+=positionposition+=1yieldcurrentdefproblem_12(min_divisors):"""Finds the first triangular number to have more than 500 divisors."""fortriangularintriangular_numbers():cur_factors=factors(triangular)iflen(cur_factors)>min_divisors:returntriangularif__name__=='__main__':printproblem_12(500)