__author__ = 'tilmannbruckhaus'

import numpy
import sys


class HighlyDivisible:

    # Highly divisible triangular number
    # Problem 12
    # The sequence of triangle numbers is generated by adding the natural numbers.
    # So the 7th triangle number would be 1 + 2 + 3 + 4 + 5 + 6 + 7 = 28.
    # The first ten terms would be:
    #
    # 1, 3, 6, 10, 15, 21, 28, 36, 45, 55, ...
    #
    # Let us list the factors of the first seven triangle numbers:
    #
    #  1: 1
    #  3: 1,3
    #  6: 1,2,3,6
    # 10: 1,2,5,10
    # 15: 1,3,5,15
    # 21: 1,3,7,21
    # 28: 1,2,4,7,14,28
    # We can see that 28 is the first triangle number to have over five divisors.
    #
    # What is the value of the first triangle number to have over five hundred divisors?
    #
    # See: http://www.wikihow.com/Determine-the-Number-of-Divisors-of-an-Integer

    def __init__(self):
        pass

    @staticmethod
    def find(limit):
        index = 1
        candidate = 1
        while True:
            factors = HighlyDivisible.factor(candidate)
            if HighlyDivisible.num_divisors(factors) > limit:
                return candidate
            index += 1
            candidate += index

    @staticmethod
    def factor(candidate):
        factors = []
        for i in range(2, int(numpy.ma.sqrt(candidate)) + 1):
            exponent = 0
            while candidate % i == 0:
                # i is a factor
                exponent += 1
                candidate /= i
            if exponent > 0:
                factors.append([i, exponent])
        if candidate > 1:
            # we are left with a prime:
            factors.append([candidate, 1])
        return factors

    @staticmethod
    def num_divisors(factors):
        num_divisors = 1
        for (divisor, exponent) in factors:
            # see wikiHow link above
            num_divisors *= exponent + 1
        return num_divisors


if __name__ == '__main__':
    count = 500
    result = HighlyDivisible.find(count)
    print "\nThe value of the first triangle number to have over", count, "divisors is", result
