"""
Author: Berdal, Ole
Created: 18.01.2019
Edited: 29.10.2019
Version: Python 3.7.4

https://projecteuler.net/problem=12:
The sequence of triangle numbers is generated by adding the natural numbers. So the 7ᵗʰ 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?
"""
import time
start_time = time.time()


def find_triangle_number_with_at_least_number_of_divisors(n_divisors):
    n, divisors_a, divisors_b = 2, 1, number_of_divisors(number=2)

    while divisors_a * divisors_b <= n_divisors:
        n += 1
        divisors_a, divisors_b = divisors_b, number_of_divisors(number=n // 2 if not n % 2 else n)

    return ((n - 1) * n) // 2


def number_of_divisors(number):
    divisor = 1
    for number_of_primes in number_of_different_primes_in_number(number=number):
        divisor *= number_of_primes + 1

    return divisor


def number_of_different_primes_in_number(number, start=3):
    prime_factors = []
    for x in range(2 if not number % 2 else start, int(number**0.5) + 1, 2):
        if not number % x:
            number //= x
            prime_factors.append(1)
            while not number % x:
                number //= x
                prime_factors[-1] += 1
            return prime_factors + number_of_different_primes_in_number(number=number, start=x + 1 + x % 2)
    else:
        return [1] if number > 1 else []


def main():
    solution = find_triangle_number_with_at_least_number_of_divisors(n_divisors=5 * 10**2)

    print('Solution: %s.\nExecution time: %s seconds.' % (solution, time.time() - start_time))


if __name__ == '__main__':
    main()
