✨ feat(euler_37.py):添加截断素数验证函数和性能计时器
♻️ refactor(euler_37.py):优化素数判断算法和代码结构 ✅ test(euler_37.py):完善截断素数检测逻辑和主程序
This commit is contained in:
@@ -9,9 +9,21 @@ 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.
|
NOTE: 2, 3, 5, and 7 are not considered to be truncatable primes.
|
||||||
"""
|
"""
|
||||||
|
|
||||||
|
import time
|
||||||
from itertools import product
|
from itertools import product
|
||||||
|
|
||||||
|
|
||||||
|
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]:
|
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)]
|
return [int(f"{x}{y}{z}") for x, y, z in product(a, b, c)]
|
||||||
@@ -27,6 +39,26 @@ def is_prime(n: int) -> bool:
|
|||||||
return True
|
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]:
|
def TruncatablePrime() -> list[int]:
|
||||||
begin = [2, 3, 5, 7]
|
begin = [2, 3, 5, 7]
|
||||||
end = [3, 7]
|
end = [3, 7]
|
||||||
@@ -40,4 +72,16 @@ def TruncatablePrime() -> list[int]:
|
|||||||
midb = [int("".join(map(str, x))) for x in midb]
|
midb = [int("".join(map(str, x))) for x in midb]
|
||||||
nums = combine_lists(begin, midb, end)
|
nums = combine_lists(begin, midb, end)
|
||||||
for num in nums:
|
for num in nums:
|
||||||
if is
|
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()
|
||||||
|
|||||||
Reference in New Issue
Block a user