Skip to content

Commit 9351889

Browse files
authored
Created problem_41 in project_euler (TheAlgorithms#2334)
* Create __init__.py * Add files via upload * Update sol1.py * Update sol1.py * Update sol1.py
1 parent 9a32f0b commit 9351889

File tree

2 files changed

+54
-0
lines changed

2 files changed

+54
-0
lines changed

project_euler/problem_41/__init__.py

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

project_euler/problem_41/sol1.py

+53
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
from math import sqrt
2+
from typing import List
3+
from itertools import permutations
4+
5+
"""
6+
We shall say that an n-digit number is pandigital if it makes use of all the digits
7+
1 to n exactly once. For example, 2143 is a 4-digit pandigital and is also prime.
8+
What is the largest n-digit pandigital prime that exists?
9+
"""
10+
11+
"""
12+
All pandigital numbers except for 1, 4 ,7 pandigital numbers are divisible by 3.
13+
So we will check only 7 digit panddigital numbers to obtain the largest possible
14+
pandigital prime.
15+
"""
16+
17+
18+
def is_prime(n: int) -> bool:
19+
"""
20+
Returns True if n is prime,
21+
False otherwise.
22+
>>> is_prime(67483)
23+
False
24+
>>> is_prime(563)
25+
True
26+
>>> is_prime(87)
27+
False
28+
"""
29+
if n % 2 == 0:
30+
return False
31+
for i in range(3, int(sqrt(n) + 1), 2):
32+
if n % i == 0:
33+
return False
34+
return True
35+
36+
37+
def compute_pandigital_primes(n: int) -> List[int]:
38+
"""
39+
Returns a list of all n-digit pandigital primes.
40+
>>> compute_pandigital_primes(2)
41+
[]
42+
>>> max(compute_pandigital_primes(4))
43+
4231
44+
>>> max(compute_pandigital_primes(7))
45+
7652413
46+
"""
47+
pandigital_str = "".join(str(i) for i in range(1, n + 1))
48+
perm_list = [int("".join(i)) for i in permutations(pandigital_str, n)]
49+
return [num for num in perm_list if is_prime(num)]
50+
51+
52+
if __name__ == "__main__":
53+
print(f"{max(compute_pandigital_primes(7)) = }")

0 commit comments

Comments
 (0)