Files
SolutionEuler/solutions/0004.palindrome/readme.md
Sidney Zhang 65999c8456 feat(project):添加欧拉项目第4、5题解决方案及文档
📝 docs(README):更新项目描述并添加核心数学理念说明
🔧 chore(pyproject.toml):更新项目描述信息
♻️ refactor(euler_3.py):改进质因数分解函数并添加类型注解
💡 docs(readme):添加第4题数学分析文档和算法说明
 test(euler_3.py):添加主函数测试用例验证质因数分解功能
2025-12-15 12:12:03 +08:00

49 lines
1.6 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

从数学角度,**快速**找到两个三位数相乘得到的最大回文数。
## 核心数学洞察
首先,两个三位数最大的乘积是: 999 × 999 = 998001 。所以最大的回文数一定是6位的。
**1. 回文数的结构性质**
一个6位回文数可以表示为
$$
\overline{abccba} = 100000a + 10000b + 1000c + 100c + 10b + a = 100001a + 10010b + 1100c = 11 \times (9091a + 910b + 100c)
$$
**关键结论**所有6位回文数都是**11的倍数**。
**2. 质因数推论**
如果乘积 $p \times q$ 是回文数且这个回文数是11的倍数那么
- 由于11是质数**p和q中至少有一个是11的倍数**
- 这样搜索空间直接缩小为原来的1/11
## 最优算法策略
```python
def largest_palindrome_product():
max_palindrome = 0
max_factors = (0, 0)
# 外层循环从大到小且只遍历11的倍数
for i in range(990, 100, -11): # 从990开始最大的11的倍数
# 内层循环从i开始避免重复利用乘法交换律
for j in range(999, i-1, -1):
product = i * j
# 提前终止:如果乘积已小于当前最大值
if product <= max_palindrome:
break
# 检查是否为回文数
if str(product) == str(product)[::-1]:
max_palindrome = product
max_factors = (i, j)
break # 找到即可跳出内层循环
return max_palindrome, max_factors
# 结果906609 = 913 × 993
```