Skip to content

Commit 5cfc017

Browse files
Kush1101cclauss
andauthored
Created problem_44 in project_euler (TheAlgorithms#2348)
* Create __int__.py * Update and rename project_euler/__int__.py to project_euler/problem_44/__int__.py * Add files via upload * Update sol1.py * Update __int__.py * Delete __int__.py * Create __init__.py * Update project_euler/problem_44/sol1.py Co-authored-by: Christian Clauss <cclauss@me.com> * Update project_euler/problem_44/sol1.py Co-authored-by: Christian Clauss <cclauss@me.com> * Update project_euler/problem_44/sol1.py Co-authored-by: Christian Clauss <cclauss@me.com> Co-authored-by: Christian Clauss <cclauss@me.com>
1 parent f8c5713 commit 5cfc017

File tree

2 files changed

+46
-0
lines changed

2 files changed

+46
-0
lines changed

project_euler/problem_44/__init__.py

+1
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
#

project_euler/problem_44/sol1.py

+45
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
"""
2+
Pentagonal numbers are generated by the formula, Pn=n(3n−1)/2. The first ten
3+
pentagonal numbers are:
4+
1, 5, 12, 22, 35, 51, 70, 92, 117, 145, ...
5+
It can be seen that P4 + P7 = 22 + 70 = 92 = P8. However, their difference,
6+
70 − 22 = 48, is not pentagonal.
7+
8+
Find the pair of pentagonal numbers, Pj and Pk, for which their sum and difference
9+
are pentagonal and D = |Pk − Pj| is minimised; what is the value of D?
10+
"""
11+
12+
13+
def is_pentagonal(n: int) -> bool:
14+
"""
15+
Returns True if n is pentagonal, False otherwise.
16+
>>> is_pentagonal(330)
17+
True
18+
>>> is_pentagonal(7683)
19+
False
20+
>>> is_pentagonal(2380)
21+
True
22+
"""
23+
root = (1 + 24 * n) ** 0.5
24+
return ((1 + root) / 6) % 1 == 0
25+
26+
27+
def compute_num(limit: int = 5000) -> int:
28+
"""
29+
Returns the minimum difference of two pentagonal numbers P1 and P2 such that
30+
P1 + P2 is pentagonal and P2 - P1 is pentagonal.
31+
>>> compute_num(5000)
32+
5482660
33+
"""
34+
pentagonal_nums = [(i * (3 * i - 1)) // 2 for i in range(1, limit)]
35+
for i, pentagonal_i in enumerate(pentagonal_nums):
36+
for j in range(i, len(pentagonal_nums)):
37+
pentagonal_j = pentagonal_nums[j]
38+
a = pentagonal_i + pentagonal_j
39+
b = pentagonal_j - pentagonal_i
40+
if is_pentagonal(a) and is_pentagonal(b):
41+
return b
42+
43+
44+
if __name__ == "__main__":
45+
print(f"{compute_num() = }")

0 commit comments

Comments
 (0)