1 Star 0 Fork 0

阿坚/projecteuler

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
p033.py 3.56 KB
一键复制 编辑 原始数据 按行查看 历史
阿坚 提交于 2022-05-13 01:42 . 37
"""
Problem 33: https://projecteuler.net/problem=33
The fraction 49/98 is a curious fraction, as an inexperienced
mathematician in attempting to simplify it may incorrectly believe
that 49/98 = 4/8, which is correct, is obtained by cancelling the 9s.
We shall consider fractions like, 30/50 = 3/5, to be trivial examples.
There are exactly four non-trivial examples of this type of fraction,
less than one in value, and containing two digits in the numerator
and denominator.
If the product of these four fractions is given in its lowest common
terms, find the value of the denominator.
"""
# _*_ conding:UTF-8 _*_
'''
@author = Kuperain
@email = kuperain@aliyun.com
@IDE = VSCODE Python3.8.3
@creat_time = 2022/5/12
'''
def solution1() -> int:
'''
in the case d=2(two digits in the numerator and denominator)
(ab)/(cd), where
(ab) < (cd), 1 <= a <= c
if a==c, (ab)/(ad) == b/d, => b=d X
if b==d, (ab)/(cb) == a/c, => a=c X
if a==d, (ab)/(ca) == b/c, => a(10c-b) = 9bc
if b==c, (ab)/(bd) == a/d, => b(10a-d) = 9ad
more generally, (a1,a2,a2,...ad)/(b1,b2,b2,...bd),
we can rule out two cases:
a1 = b1 X
ad = bd X
'''
finds = list()
for m in range(10, 99):
if m % 10 == 0:
continue
for n in range(m+1, 99):
ms = str(m)
ns = str(n)
if len(set(ms + ns)) == 4:
# print(f'{m},{n} do not have same digit.')
continue
for i in range(2):
for j in range(2):
if ms[i] == ns[j]:
# print(f'{m},{n},both have {ms[i]}.')
ms1 = list(ms)
ms1.remove(ms[i])
m1 = int(''.join(ms1))
ns1 = list(ns)
ns1.remove(ns[j])
n1 = int(''.join(ns1))
if n1 != 0 and m*n1 == n*m1:
finds.append((m, n))
print(finds)
# [(16, 64), (19, 95), (26, 65), (49, 98)]
p, q = 1, 1
for fract in finds:
p *= fract[0]
q *= fract[1]
# print(p, q)
# 387296 38729600
import math
return q//math.gcd(p, q)
def solution2(dm: int = 2, dn: int = 2) -> int:
'''
(a1,a2,a2,...a_dm)/(b1,b2,b2,...b_dn)
'''
if dm > dn:
raise ValueError('m < n')
finds = set()
for m in range(10**(dm-1), 10**dm):
for n in range(max(m+1, 10**(dn-1)), 10**dn):
# dm=dm-1, dn=dn-1, not belong (dm,dn) case
if m % 10 == 0 or n % 10 == 0:
continue
ms = str(m)
ns = str(n)
for i in range(dm):
if i < dm-1 and ms[i+1] == ms[i]:
continue
for j in range(dn):
if j < dn-1 and ns[j+1] == ns[j]:
continue
if ms[i] == ns[j]:
msl = list(ms)
msl.pop(i)
msl = int(''.join(msl))
nsl = list(ns)
nsl.pop(j)
nsl = int(''.join(nsl))
if m*nsl == n*msl:
if (m, n) in finds:
print(m, n)
finds.add((m, n, int(ms[i])))
print(len(finds))
return finds
if __name__ == "__main__":
import doctest
doctest.testmod(verbose=False)
print(solution1())
# 100
solution2(3, 3)
# 245
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
Python
1
https://gitee.com/kuperain/projecteuler.git
git@gitee.com:kuperain/projecteuler.git
kuperain
projecteuler
projecteuler
master

搜索帮助