TheAlgorithms-Python

Форк
0
77 строк · 2.0 Кб
1
"""
2
Pandigital prime
3
Problem 41: https://projecteuler.net/problem=41
4

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

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

14
from __future__ import annotations
15

16
import math
17
from itertools import permutations
18

19

20
def is_prime(number: int) -> bool:
21
    """Checks to see if a number is a prime in O(sqrt(n)).
22

23
    A number is prime if it has exactly two factors: 1 and itself.
24

25
    >>> is_prime(0)
26
    False
27
    >>> is_prime(1)
28
    False
29
    >>> is_prime(2)
30
    True
31
    >>> is_prime(3)
32
    True
33
    >>> is_prime(27)
34
    False
35
    >>> is_prime(87)
36
    False
37
    >>> is_prime(563)
38
    True
39
    >>> is_prime(2999)
40
    True
41
    >>> is_prime(67483)
42
    False
43
    """
44

45
    if 1 < number < 4:
46
        # 2 and 3 are primes
47
        return True
48
    elif number < 2 or number % 2 == 0 or number % 3 == 0:
49
        # Negatives, 0, 1, all even numbers, all multiples of 3 are not primes
50
        return False
51

52
    # All primes number are in format of 6k +/- 1
53
    for i in range(5, int(math.sqrt(number) + 1), 6):
54
        if number % i == 0 or number % (i + 2) == 0:
55
            return False
56
    return True
57

58

59
def solution(n: int = 7) -> int:
60
    """
61
    Returns the maximum pandigital prime number of length n.
62
    If there are none, then it will return 0.
63
    >>> solution(2)
64
    0
65
    >>> solution(4)
66
    4231
67
    >>> solution(7)
68
    7652413
69
    """
70
    pandigital_str = "".join(str(i) for i in range(1, n + 1))
71
    perm_list = [int("".join(i)) for i in permutations(pandigital_str, n)]
72
    pandigitals = [num for num in perm_list if is_prime(num)]
73
    return max(pandigitals) if pandigitals else 0
74

75

76
if __name__ == "__main__":
77
    print(f"{solution() = }")
78

Использование cookies

Мы используем файлы cookie в соответствии с Политикой конфиденциальности и Политикой использования cookies.

Нажимая кнопку «Принимаю», Вы даете АО «СберТех» согласие на обработку Ваших персональных данных в целях совершенствования нашего веб-сайта и Сервиса GitVerse, а также повышения удобства их использования.

Запретить использование cookies Вы можете самостоятельно в настройках Вашего браузера.