From 5b1a9f0e4ee23d1a522ac55ad6b7200b09e937cc Mon Sep 17 00:00:00 2001 From: Sidney Zhang Date: Wed, 7 Jan 2026 18:33:01 +0800 Subject: [PATCH] =?UTF-8?q?=E2=9C=A8=20feat(euler=5F37.py)=EF=BC=9A?= =?UTF-8?q?=E6=B7=BB=E5=8A=A0=E6=88=AA=E6=96=AD=E7=B4=A0=E6=95=B0=E9=AA=8C?= =?UTF-8?q?=E8=AF=81=E5=87=BD=E6=95=B0=E5=92=8C=E6=80=A7=E8=83=BD=E8=AE=A1?= =?UTF-8?q?=E6=97=B6=E5=99=A8=20=E2=99=BB=EF=B8=8F=20refactor(euler=5F37.p?= =?UTF-8?q?y)=EF=BC=9A=E4=BC=98=E5=8C=96=E7=B4=A0=E6=95=B0=E5=88=A4?= =?UTF-8?q?=E6=96=AD=E7=AE=97=E6=B3=95=E5=92=8C=E4=BB=A3=E7=A0=81=E7=BB=93?= =?UTF-8?q?=E6=9E=84=20=E2=9C=85=20test(euler=5F37.py)=EF=BC=9A=E5=AE=8C?= =?UTF-8?q?=E5=96=84=E6=88=AA=E6=96=AD=E7=B4=A0=E6=95=B0=E6=A3=80=E6=B5=8B?= =?UTF-8?q?=E9=80=BB=E8=BE=91=E5=92=8C=E4=B8=BB=E7=A8=8B=E5=BA=8F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- solutions/0037.TruncatablePrimes/euler_37.py | 52 ++++++++++++++++++-- 1 file changed, 48 insertions(+), 4 deletions(-) diff --git a/solutions/0037.TruncatablePrimes/euler_37.py b/solutions/0037.TruncatablePrimes/euler_37.py index 377e9c2..c5799c2 100644 --- a/solutions/0037.TruncatablePrimes/euler_37.py +++ b/solutions/0037.TruncatablePrimes/euler_37.py @@ -9,10 +9,22 @@ Find the sum of the only eleven primes that are both truncatable from left to ri NOTE: 2, 3, 5, and 7 are not considered to be truncatable primes. """ +import time from itertools import product -def combine_lists(a: list[int], b: list[int|None], c: list[int]) -> list[int]: +def timer(func): + def wrapper(*args, **kwargs): + start_time = time.time() + result = func(*args, **kwargs) + end_time = time.time() + print(f"Time taken: {end_time - start_time:.6f} seconds") + return result + + return wrapper + + +def combine_lists(a: list[int], b: list[int | None], c: list[int]) -> list[int]: """将三个列表的每个元素组合成数字""" return [int(f"{x}{y}{z}") for x, y, z in product(a, b, c)] @@ -21,12 +33,32 @@ def is_prime(n: int) -> bool: """判断一个数是否为素数""" if n < 2: return False - for i in range(2, int(n ** 0.5) + 1): + for i in range(2, int(n**0.5) + 1): if n % i == 0: return False return True +def truncate_left(n: int) -> bool: + """从左到右截断一个数""" + length = len(str(n)) + while n > 0: + if not is_prime(n): + return False + n %= 10 ** (length - 1) + length -= 1 + return True + + +def truncate_right(n: int) -> bool: + """从右到左截断一个数""" + while n > 0: + if not is_prime(n): + return False + n //= 10 + return True + + def TruncatablePrime() -> list[int]: begin = [2, 3, 5, 7] end = [3, 7] @@ -39,5 +71,17 @@ def TruncatablePrime() -> list[int]: midb = product(middle, repeat=length - 2) midb = [int("".join(map(str, x))) for x in midb] nums = combine_lists(begin, midb, end) - for num in nums : - if is + for num in nums: + if is_prime(num): + if truncate_left(num) and truncate_right(num): + res.append(num) + return res + + +@timer +def main(): + print(sum(TruncatablePrime())) + + +if __name__ == "__main__": + main()