-
Notifications
You must be signed in to change notification settings - Fork 0
/
Problem045.py
executable file
·45 lines (37 loc) · 1.09 KB
/
Problem045.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
#!/usr/bin/python3
#coding:utf8
# http://projecteuler.net/problem=45
#
# PROBLEM CONTENT:
# Triangle, pentagonal, and hexagonal numbers are generated by the following
# formulae:
# Triangle: Tn = n*(n+1)/2
# Pentagonal: Pn = n*(3*n-1)/2
# Hexagonal: Hn = n*(2n-1)
#
# It can be verified that T285 = P165 = H143 = 40755
#
# Find the next triangle number that is also pentagonal and hexagonal.
# EXPLANATION:
# Hexagonal numbers grow the faster. Starting with the given example, we
# iterate to the next hexagonal number and we check if it is triangular and
# pentagonal as well
import time
from math import sqrt
def is_triangular(c):
return ((-1+sqrt(1+8*c))/2).is_integer()
def is_pentagonal(c):
return ((1 + sqrt(1+24*c))/6).is_integer()
def main():
n = 143
while True:
n += 1
hexagonal = n*(2*n-1)
if (is_triangular(hexagonal) and is_pentagonal(hexagonal)):
print(hexagonal)
return
if __name__ == '__main__':
start = time.time()
main()
elapsed = time.time() - start
print('Solved in %.2f seconds' % elapsed)