Euler Solution 33

From ProgSoc Wiki

Jump to: navigation, search

Solutions for 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.

Ruby by tomchristmas

Runtime: 148ms (on kali).

fract = []

      if numer.to_s[1,1] != "0" && denom.to_s[1,1] != "0" # trivial case 
             if (numer.to_s[x,1] == denom.to_s[y,1]) &&
                (numer.to_s[1-x,1].to_f/denom.to_s[1-y,1].to_f == numer.to_f/denom.to_f)
                 fract << numer << denom

puts fract
puts (fract[0]*fract[2]*fract[4]*fract[6]).to_f/(fract[1]*fract[3]*fract[5]*fract[7])

Python by Althalus

Runtime: 82ms

import time
start_time = time.time()

#Unorthodox cancelling method.
#Basically, screwing up the cancelling.
#49 / 98 - cancel the 9's, 4/8. Correct answer.
#Trivial example is 30/50. (ie any where we cancel the 2 0's)
#There are 4 non-trivial examples where numerator + denominator are 2 digits each and the fraction is less than 1.

def unorthodox(list):
        result = []
        numerator = [int(c) for c in str(list[0])]
        denominator = [int(c) for c in str(list[1])]
        for i,c in enumerate(numerator):
                if c not in denominator:
        for i,c in enumerate(denominator):
                if c not in numerator:
        if len(result) != 2: return False
        if result[1] == 0: return False
        if result[0]/float(result[1]) == list[0]/float(list[1]): return True
        return False

def GCD(a,b):
        while b != 0:
                tmp = a % b
                a = b
                b = tmp
        return a

dlist = []
nlist = []
for i in range(10,100):
        for j in range(10,i):
                if unorthodox([j,i]) and (i%10 != 0 or j%10 != 0):
ntotal, dtotal = 1,1

for n in nlist:
        ntotal *= n
for d in dlist:
        dtotal *= d

print dtotal/GCD(ntotal,dtotal)

run_time = time.time() - start_time
print run_time
Personal tools