Skip to content

[Project Euler] Fix code style in Problem 41 #2992

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 8 commits into from
Oct 8, 2020
Merged
Changes from 5 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 23 additions & 9 deletions project_euler/problem_41/sol1.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,14 +4,15 @@
from math import sqrt

"""
Pandigital prime
Problem 41: https://projecteuler.net/problem=41

We shall say that an n-digit number is pandigital if it makes use of all the digits
1 to n exactly once. For example, 2143 is a 4-digit pandigital and is also prime.
What is the largest n-digit pandigital prime that exists?
"""

"""
All pandigital numbers except for 1, 4 ,7 pandigital numbers are divisible by 3.
So we will check only 7 digit panddigital numbers to obtain the largest possible
So we will check only 7 digit pandigital numbers to obtain the largest possible
pandigital prime.
"""

Expand All @@ -37,18 +38,31 @@ def is_prime(n: int) -> bool:

def compute_pandigital_primes(n: int) -> list[int]:
"""
Returns a list of all n-digit pandigital primes.
Returns a list of all pandigital prime numbers of length n.
>>> compute_pandigital_primes(2)
[]
>>> max(compute_pandigital_primes(4))
4231
>>> max(compute_pandigital_primes(7))
7652413
>>> compute_pandigital_primes(4)
[1423, 2143, 2341, 4231]
"""
pandigital_str = "".join(str(i) for i in range(1, n + 1))
perm_list = [int("".join(i)) for i in permutations(pandigital_str, n)]
return [num for num in perm_list if is_prime(num)]


def solution(n: int = 7) -> int:
"""
Returns the maximum pandigital prime number of length n
If no pandigitals exist the returned value is zero.
>>> solution(2)
0
>>> solution(4)
4231
>>> solution(7)
7652413
"""
pandigital_primes = compute_pandigital_primes(n)
return max(pandigital_primes) if pandigital_primes else 0


if __name__ == "__main__":
print(f"{max(compute_pandigital_primes(7)) = }")
print(f"{solution()}")