#!/usr/bin/env python
'''
    https://projecteuler.net/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?

    $ time ./12.py -n 500
    n : 500
    76576500

    real    0m0.186s
    user    0m0.180s
    sys     0m0.004s
'''
import argparse
import math

parser = argparse.ArgumentParser()

parser.add_argument('-n', action='store', dest='n',
                    default=10,
                    help='n, number')

cmd_args = parser.parse_args()
N = int(cmd_args.n)

print("n : {}".format(N))

def divisor_function(n):

    count = 1
    exp = 0
    if n % 2 == 0:
        exp = exp + 1
        n = n / 2
        while n % 2 == 0 :
            exp = exp + 1
            n = n / 2

    count = count * (exp + 1)
    factor = 3
    max_factor = math.sqrt(n)

    while n > 1 and factor <= max_factor:
        exp = 0
        if n % factor == 0:
            exp = exp + 1
            n = n / factor
            while n % factor == 0:
                exp = exp + 1
                n = n / factor
            max_factor = math.sqrt(n)

            count = count * (exp + 1)
        factor = factor + 2

    if n != 1:
        count = count * (1 + 1)

    return count

sum = 0
n = 1
while True:
    sum = sum + n
    if divisor_function(sum) >= N :
        print sum
        break
    n = n + 1
