-
Notifications
You must be signed in to change notification settings - Fork 0
/
Question_12.py
67 lines (53 loc) · 2.42 KB
/
Question_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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
from functools import reduce
"""
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, ...
What is the value of the first triangle number to have over five hundred divisors?
"""
def number_of_divisors(num_div):
# to get number of divisors of a number add 1 to power of
# it's prime divisors. For more details go =>
# https://en.wikipedia.org/wiki/Divisor_function
# therefore we will get only power of prime divisors for each number
prime_divisors = list()
# to find prime divisors
for i in range(2, int(num_div**0.5)+1):
i_count = 0
# if i divide num_div => then it will be a prime
# because we will redivide until new num_div not divisible by i
# and ofcourse it's power
while num_div%i == 0:
num_div /= i
# increase i_count which represent i power in the original number
i_count += 1
if i_count:
prime_divisors.append(i_count)
# # # # # # # # # # # # # # # # # # # # # # # # # # # # #
# WE CAN INCREASE PERFORMANCE OF THE FOR LOOP BY #
# range(3, int(num**0.5),2) OR SOME OTHER METHODS #
# (e.g. GET PRIME LIST JUST ONCE AT THE BEGINNING) #
# BUT AS WE GET ANSWER IN LESS THAN 5 SECONDS, I DIDN'T #
# TRY TO OPTIMIZE IT. #
# # # # # # # # # # # # # # # # # # # # # # # # # # # # #
# then increase each power by one
prime_divisors = [i+1 for i in prime_divisors]
# and multiply by reduce method.
# To avoid empty list we can use list comprehension method
return reduce(lambda x, y: x*y, prime_divisors) if len(prime_divisors) > 0 else 0
if __name__ == '__main__':
# result will get the answer of the question when program done
# count is used to get next triangle number, it is increasing step
result, count = 0, 1
# the while loop will run until it find the answer
while True:
result += count
count += 1
# send the number to get number of it's divisors
if(number_of_divisors(result)) > 500:
# if number of divisors for number higher than 500
# break the lııp
break
# print the answer
print(f'Answer to Question 12 is {result}')