feat(cli): 支持多重目录结构与特殊解法运行,新增解法列表选项

This commit is contained in:
2026-03-04 16:52:33 +08:00
parent cc6b5a1fbf
commit 88df32be36
5 changed files with 16684 additions and 13 deletions

65
main.py
View File

@@ -62,16 +62,61 @@ def list_problems(every: bool = False):
@app.command("solution", help="Run a solution for a given problem.")
def run_solution(num: int) -> None:
folders = list(Path("solutions").iterdir())
folders = [
folder
for folder in folders
if folder.is_dir() and folder.name.startswith(f"{num:04d}")
]
runpy.run_path(
(folders[0] / f"euler_{num}.py").resolve().as_posix(), run_name="__main__"
)
def run_solution(
num: int,
special: None | str = None,
list_solutions: bool = False,
) -> None:
# Find target folders that match the problem number
target_folders = []
for folder in Path("solutions").iterdir():
if not folder.is_dir():
continue
# Check for exact match (e.g., "0001")
if folder.name.startswith(f"{num:04d}"):
target_folders.append(folder)
break
# Check for range folders (e.g., "0001_0050")
if "_" in folder.name:
try:
start_str, end_str = folder.name.split("_")
start_num = int(start_str)
end_num = int(end_str)
if start_num <= num <= end_num:
for subfolder in folder.iterdir():
if subfolder.is_dir() and subfolder.name.startswith(
f"{num:04d}"
):
target_folders.append(subfolder)
break
except (ValueError, IndexError):
continue
if not target_folders:
typer.echo(f"No folder found for problem {num}")
return
target_folder = target_folders[0]
if list_solutions:
# List all Python files in the target folder
for file in target_folder.iterdir():
if file.is_file() and file.suffix == ".py":
typer.echo(f"{file.name}")
return
# Determine the filename to run
filename = f"euler_{num}.py"
if special:
filename = f"euler_{num}_{special}.py"
file_path = target_folder / filename
if not file_path.exists():
typer.echo(f"Solution file not found: {file_path}")
return
# Run the solution
runpy.run_path(file_path.resolve().as_posix(), run_name="__main__")
@app.command("version", help="Display the version of the projecteuler CLI.")

View File

@@ -115,4 +115,4 @@ def get_prime_factors(n: int) -> Set[int | None]:
if __name__ == "__main__":
print(get_prime_factors(60)) # {2, 3, 5}
print(get_prime_factors(600851475143)) # {2, 3, 5}

View File

@@ -70,8 +70,8 @@ def main():
for i, v in enumerate(primes):
if v == max_sp:
break
gap = int((max_sp - v) / 3)
for g in range(gap, (primes[i + 1] - v - 1), -1):
gap = (max_sp - v) // 2
for g in range(gap, 0, -1):
if v + g in primes and v + 2 * g in primes:
if list_com(list(str(v)), list(str(v + g))):
if list_com(list(str(v)), list(str(v + 2 * g))):

View File

@@ -0,0 +1,106 @@
"""
The arithmetic sequence, 1487,4817,8147, in which each of the terms increases by 3330,
is unusual in two ways: (i) each of the three terms are prime, and, (ii) each of the
4-digit numbers are permutations of one another.
There are no arithmetic sequences made up of three 1-, 2-, or 3-digit primes, exhibiting this property,
but there is one other 4-digit increasing sequence.
What 12-digit number do you form by concatenating the three terms in this sequence?
"""
import time
from logging import root
from pathlib import Path
def timer(func):
def wrapper(*args, **kwargs):
start_time = time.time()
result = func(*args, **kwargs)
end_time = time.time()
elapsed_time = end_time - start_time
print(f"{func.__name__} time: {elapsed_time:.6f} seconds")
return result
return wrapper
@timer
def solve_ultra_optimized(n: int = 4) -> list[str]:
limit = 10**n
mini_limit = 10 ** (n - 1) + 1
# ========== 1. Bitset 筛法(内存高效) ==========
is_prime = bytearray(b"\x01") * limit
is_prime[0] = is_prime[1] = 0
# 埃氏筛,使用切片赋值加速
for i in range(2, int(limit**0.5) + 1):
if is_prime[i]:
start = i * i
is_prime[start:limit:i] = b"\x00" * ((limit - start - 1) // i + 1)
# ========== 2. 按数字签名分组 ==========
groups = {}
for p in range(mini_limit, limit, 2): # 只遍历奇数4位质数必为奇数
if is_prime[p]:
key = "".join(sorted(str(p)))
groups.setdefault(key, []).append(p)
# ========== 3. 组内搜索利用模18剪枝 ==========
res = []
for key, group in groups.items():
if len(group) < 3:
continue
group.sort()
group_set = set(group) # 用于O(1)成员检查
n = len(group)
for i in range(n):
a = group[i]
for j in range(i + 1, n):
b = group[j]
d = b - a
# 核心数学优化公差必须是18的倍数
# 原因:(1) 排列数字和相同 => 模9同余 => d%9==0
# (2) 质数>2都是奇数 => 奇+偶=奇 => d%2==0
if d % 18 != 0:
continue
c = b + d
# 边界检查利用group有序性提前终止
if c >= limit:
break
# Bitset O(1) 质数检查
if not is_prime[c]:
continue
# 确认第三项在组内(数字签名匹配)
if c in group_set:
res.append(f"{a}-{b}-{c}:{d}")
return res
if __name__ == "__main__":
try:
n = int(input("Search digits (default is 4-digit): ") or "4")
except ValueError:
n = 4
res = solve_ultra_optimized(n)
if lr := len(res) > 10:
head = 10
print(
f"Too much data, only showing the first ten rows. Other data saved in result_{n}_digit.txt."
)
root_path = Path(__file__).parent
with open(f"{root_path}/result_{n}_digit.txt", "w", encoding="utf-8") as f:
f.write("\n".join(res))
else:
head = lr
for x in res[:head]:
print(x)

File diff suppressed because it is too large Load Diff