from tools import number_theory def is_prime(num, prime): for p in prime: if p ** 2 > num: return True if not (num % p): return False def gen_p(digit): l = list(reversed(range(1, digit + 1))) not_ordered = True while not_ordered: yield int(''.join(map(lambda x: str(x), l))) for i in range(len(l) - 1, 0, -1): if l[i - 1] > l[i]: post = list(sorted(l[i - 1:])) get = post.pop(post.index(l[i - 1]) - 1) l = l[:i - 1] + [get] + list(reversed(post)) break else: not_ordered = False def find(): prime = list(number_theory.make_prime(10000)) for digit in range(8, 3, -1): if digit % 3: for x in gen_p(digit): if is_prime(x, prime): return x print(find())