-
Notifications
You must be signed in to change notification settings - Fork 0
/
E_12.py
39 lines (34 loc) · 1.1 KB
/
E_12.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
# -*- coding: utf-8 -*-
"""
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,...
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
import math
def check_divisors(num):
divisors = 2
# To save time, check divisors only until its square root
sqrt_num = int(math.sqrt(num))
for i in range (2, sqrt_num + 1):
if num % i == 0:
divisors += 2 # i and num/i
if sqrt_num * sqrt_num == num: # Putting this if outside of for saves 50% of time
divisors -= 1
return divisors
def find_triangle_num(divisors_wanted):
num = 1
i = 1
while check_divisors(num) <= divisors_wanted:
i += 1
num += i
return num
start_time = time.time()
found_triangle = find_triangle_num(500)
print(found_triangle)
end_time = time.time()
total_time = end_time - start_time
print(total_time)