📝 docs(README):更新项目描述并添加核心数学理念说明 🔧 chore(pyproject.toml):更新项目描述信息 ♻️ refactor(euler_3.py):改进质因数分解函数并添加类型注解 💡 docs(readme):添加第4题数学分析文档和算法说明 ✅ test(euler_3.py):添加主函数测试用例验证质因数分解功能
68 lines
1.5 KiB
Python
68 lines
1.5 KiB
Python
"""
|
||
2520 is the smallest number that can be divided by each of the numbers from 1 to 10 without any remainder.
|
||
What is the smallest positive number that is evenly divisible by all of the numbers from 1 to 20?
|
||
"""
|
||
|
||
import math
|
||
import random
|
||
|
||
|
||
def is_probable_prime(n: int, trials: int = 10) -> bool:
|
||
"""Miller-Rabin素性测试(快速判断是否为质数)"""
|
||
if n < 2:
|
||
return False
|
||
if n in (2, 3):
|
||
return True
|
||
if n % 2 == 0:
|
||
return False
|
||
|
||
# 将 n-1 写成 d * 2^s 的形式
|
||
d = n - 1
|
||
s = 0
|
||
while d % 2 == 0:
|
||
d //= 2
|
||
s += 1
|
||
|
||
# 测试
|
||
for _ in range(trials):
|
||
a = random.randrange(2, n - 1)
|
||
x = pow(a, d, n)
|
||
if x == 1 or x == n - 1:
|
||
continue
|
||
for _ in range(s - 1):
|
||
x = pow(x, 2, n)
|
||
if x == n - 1:
|
||
break
|
||
else:
|
||
return False
|
||
return True
|
||
|
||
|
||
def primes_up_to(n: int) -> list[int]:
|
||
if n < 2:
|
||
return []
|
||
if n == 2:
|
||
return [2]
|
||
if n == 3:
|
||
return [2, 3]
|
||
|
||
primes = [2, 3]
|
||
for i in range(5, n + 1, 2):
|
||
if is_probable_prime(i):
|
||
primes.append(i)
|
||
|
||
return primes
|
||
|
||
|
||
def smallest_multiple(n: int) -> int:
|
||
result = 1
|
||
for p in primes_up_to(n):
|
||
# 找出最大幂次
|
||
exp = int(math.log(n, p))
|
||
result *= p**exp
|
||
return result
|
||
|
||
|
||
if __name__ == "__main__":
|
||
print(smallest_multiple(20))
|