1 Star 0 Fork 0

阿坚/projecteuler

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
p004.py 2.36 KB
一键复制 编辑 原始数据 按行查看 历史
阿坚 提交于 2022-05-05 00:06 . 4 5
"""
Project Euler Problem 4: https://projecteuler.net/problem=4
Largest palindrome product
A palindromic number reads the same both ways. The largest palindrome made
from the product of two 2-digit numbers is 9009 = 91 × 99.
Find the largest palindrome made from the product of two 3-digit numbers.
"""
# _*_ conding:UTF-8 _*_
'''
@author = Kuperain
@email = kuperain@aliyun.com
@IDE = Thonny Python3.8
@creat_time = 2022/5/4
'''
def isPalindromicNumber(n: int) -> bool:
'''
>>> isPalindromicNumber(12321)
True
>>> isPalindromicNumber(1221)
True
>>> isPalindromicNumber(1234326)
False
>>> isPalindromicNumber(1230)
False
'''
if n%10 == 0:
return False
nStr = str(n)
halfLen = len(nStr)//2
for i in range(halfLen):
if nStr[i] == nStr[-(i+1)]:
continue
else:
return False
return True
def solution1(b: int = 3) -> int:
maxNum = 10**b - 1
minNum = 10**(b-1)
res = (0, 0, 0)
for i in range(maxNum,minNum,-1):
if i%10 == 0:
continue
for j in range(maxNum,minNum,-1):
if j%10 == 0:
continue
if isPalindromicNumber(i*j):
res = (i, j, i*j) if i*j>res[2] else res
return res
def solution2(b: int = 3) -> int:
maxNum = 10**b - 1
minNum = 10**(b-1)
res = maxNum**2
res_min = minNum**2
while res > res_min:
if isPalindromicNumber(res):
factor = maxNum
factor_min = minNum
while factor > factor_min:
if factor % 10 == 0:
factor = factor - 1
continue
tmp = divmod(res, factor)
if tmp[1] == 0 and len(str(tmp[0]))== b:
return factor, tmp[0], res
factor = factor - 1
res = res - 1
return
if __name__ == "__main__":
import doctest, time
doctest.testmod(verbose = True)
start = time.time()
print(f"{solution1() = }")
time1 = time.time()
print(f'耗时:{time1 - start}s')
print(f"{solution2() = }")
time2 = time.time()
print(f'耗时:{time2 - time1}s')
'''
solution1() = (993, 913, 906609)
耗时:1.6720037460327148s
solution2() = (993, 913, 906609)
耗时:0.26000046730041504s
'''
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
Python
1
https://gitee.com/kuperain/projecteuler.git
git@gitee.com:kuperain/projecteuler.git
kuperain
projecteuler
projecteuler
master

搜索帮助