From 5cfc017ebb51b7107c2c930df94ab18ef5e3c88c Mon Sep 17 00:00:00 2001 From: Kushagra Bansal Date: Tue, 25 Aug 2020 13:16:13 +0530 Subject: [PATCH] Created problem_44 in project_euler (#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 * Update project_euler/problem_44/sol1.py Co-authored-by: Christian Clauss * Update project_euler/problem_44/sol1.py Co-authored-by: Christian Clauss Co-authored-by: Christian Clauss --- project_euler/problem_44/__init__.py | 1 + project_euler/problem_44/sol1.py | 45 ++++++++++++++++++++++++++++ 2 files changed, 46 insertions(+) create mode 100644 project_euler/problem_44/__init__.py create mode 100644 project_euler/problem_44/sol1.py diff --git a/project_euler/problem_44/__init__.py b/project_euler/problem_44/__init__.py new file mode 100644 index 000000000..792d60054 --- /dev/null +++ b/project_euler/problem_44/__init__.py @@ -0,0 +1 @@ +# diff --git a/project_euler/problem_44/sol1.py b/project_euler/problem_44/sol1.py new file mode 100644 index 000000000..536720b39 --- /dev/null +++ b/project_euler/problem_44/sol1.py @@ -0,0 +1,45 @@ +""" +Pentagonal numbers are generated by the formula, Pn=n(3nāˆ’1)/2. The first ten +pentagonal numbers are: +1, 5, 12, 22, 35, 51, 70, 92, 117, 145, ... +It can be seen that P4 + P7 = 22 + 70 = 92 = P8. However, their difference, +70 āˆ’ 22 = 48, is not pentagonal. + +Find the pair of pentagonal numbers, Pj and Pk, for which their sum and difference +are pentagonal and D = |Pk āˆ’ Pj| is minimised; what is the value of D? +""" + + +def is_pentagonal(n: int) -> bool: + """ + Returns True if n is pentagonal, False otherwise. + >>> is_pentagonal(330) + True + >>> is_pentagonal(7683) + False + >>> is_pentagonal(2380) + True + """ + root = (1 + 24 * n) ** 0.5 + return ((1 + root) / 6) % 1 == 0 + + +def compute_num(limit: int = 5000) -> int: + """ + Returns the minimum difference of two pentagonal numbers P1 and P2 such that + P1 + P2 is pentagonal and P2 - P1 is pentagonal. + >>> compute_num(5000) + 5482660 + """ + pentagonal_nums = [(i * (3 * i - 1)) // 2 for i in range(1, limit)] + for i, pentagonal_i in enumerate(pentagonal_nums): + for j in range(i, len(pentagonal_nums)): + pentagonal_j = pentagonal_nums[j] + a = pentagonal_i + pentagonal_j + b = pentagonal_j - pentagonal_i + if is_pentagonal(a) and is_pentagonal(b): + return b + + +if __name__ == "__main__": + print(f"{compute_num() = }")