Problem:
The fraction \$(\dfrac{49}{98})\$ is a curious fraction, as an inexperienced mathematician in attempting to simplify it may incorrectly believe that \$(\dfrac{49}{98}) = (\dfrac{4}{8})\$, which is correct, is obtained by cancelling the 9s.
We shall consider fractions like, \$(\dfrac{30}{50}) = (\dfrac{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.
This is some rough code -- this one was a lot harder than I expected it to be. Please help me optimize.
from timeit import default_timer as timer
start = timer()
fractions_that_work = []
def a_common_element(list_a, list_b):
count = 0
common = 0
for m in list_a:
for n in list_b:
if m == n:
count += 1
common = m
if count == 1:
return common
return False
for numerator in range(10, 100):
for denominator in range(numerator + 1, 100): # denom must be > num
n_digits = sorted([int(x) for x in str(numerator)])
d_digits = sorted([int(x) for x in str(denominator)])
common = a_common_element(n_digits, d_digits)
if common:
n_digits.remove(common)
d_digits.remove(common)
n_rem = n_digits[0]
d_rem = d_digits[0]
if 0 not in n_digits and 0 not in d_digits:
if float(numerator) / denominator == float(n_rem) / d_rem:
fractions_that_work.append([numerator, denominator])
product_of_fractions = [1, 1]
for frac in fractions_that_work:
product_of_fractions[0] *= frac[0]
product_of_fractions[1] *= frac[1]
start = timer()
ans = product_of_fractions[1] / product_of_fractions[0]
elapsed_time = (timer() - start) * 1000 # s --> ms
print "Found %d in %r ms." % (ans, elapsed_time)
start = timer()
is a mistake. Keeping the code in the answer as it is unless a mod thinks it's better to change it. \$\endgroup\$