The fraction 49/98 is a curious fraction, as an inexperienced mathematician in attempting to simplify it may incorrectly believe that49/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.
没什么好思路。一句话,死算呗:
import datetime
import fractions
start_time=datetime.datetime.now()
templist=[ x for x in xrange(10,100) if len(set(str(x)))>1]
relist=[]
for yindex, y in enumerate(templist):
if yindex==0:
continue
y_str=str(y)
y_set=set(y_str)
for x in templist[:yindex]:
x_str=str(x)
x_set=set(x_str)
inter=x_set&y_set
if not inter:
continue
interlist=list(inter)
for tempvalue in interlist:
if y_set-set([tempvalue])!={'0'}:
orgin_fra=fractions.Fraction(x,y)
final_fra=fractions.Fraction(int(list(x_set-set([tempvalue]))[0]),int(list(y_set-set([tempvalue]))[0]))
if orgin_fra==final_fra:
relist.append((x,y))
def maxdivisor(x,y):
if x%y==0:
return y
return maxdivisor(max(x%y,y),min(x%y,y))
relist=[(x,y) for x,y in relist if x*y%100]
print relist
x,y=1,1
for tempx,tempy in relist:
x*=tempx/maxdivisor(tempy,tempx)
y*=tempy/maxdivisor(tempy,tempx)
print y/maxdivisor(y,x)
end_time=datetime.datetime.now()
print end_time-start_time
运行结果为:
[(16, 64), (26, 65), (19, 95), (49, 98)]
100
0:00:00.043000
别人的代码:
import math,time
t=time.time()
def red(r): #does a/b reduce, where r = a,b, [a,b],etc
a,b = r
x = (set(str(a)) & set(str(b))) - set(['0'])
for n in x:
a1 = filter(lambda z:str(a)[(z+1)%2] == n,[0,1])
a2 = filter(lambda z:str(b)[(z+1)%2] == n,[0,1])
for c in a1:
for d in a2:
if a*int(str(b)[d]) == b*int(str(a)[c]):
return(True)
return(False)
def red2(r): # reduce a/b to lowest terms, where r= a,b, etc
(a,b) = r
#a,b=max(a,b),min(a,b)
maxd=getmaxdivisor(b,a)
return b/maxd
def getmaxdivisor(a,b):
if a%b==0:
return b
else:
return getmaxdivisor(max(a%b,b),min(a%b,b))
sols = filter(red,[(a,b) for a in range(10,100) for b in range(a+1,100)])
sol = red2([reduce(lambda a,b:a*b,[x[k] for x in sols]) for k in [0,1]])
print sols
print sol
print time.time()-t
运行结果:
[(16, 64), (19, 95), (26, 65), (49, 98)]
100
0.0210001468658
。。比我快一倍了。我了个去了。