Curious Fractions

While suffering from conjuctivitis, fever, a sore throat and what seems to be a case of swollen tonsils determined to make nutrition a pain for the next week or two, I decided to solve a problem on Project Euler. The question I picked was Problem 33: Find all fractions with the given unorthodox cancelling method (just click the fscking link for heaven’s sake!).

I thought this problem can be solved by beginning with a base fraction and adding a numbers in the tens place to both the numerator and the denominator, then adding a number in the units place to the numerator and the denominator, adding to the units place in the numerator and the tens in the denominator and the other way round.

The code needed (in Python2.6 – just love the Fractions module there):

#!/usr/bin/env python
#Author: Shriphani Palakodety
#Blog: http://shriphani.com/blog
#Mail: shriphani@shriphani.com

frac_list = []

from fractions import Fraction

prod = 1

def findLeft(num, den):
    ‘Given a denominator, numerator pair, return the double digit possibilities by appending chars to the left’
    global prod
    for i in xrange(1, 10):
        if i == num or i == den:
            continue
        else:
            if Fraction(10*i+num, 10*i+den)==Fraction(num, den):
                frac_list.append(Fraction(num, den))
                print num,den

def findRight(num, den):
    global prod
    for i in xrange(1, 10):
        if i == num or i == den:
            continue
        else:
            if Fraction(10*num+i, 10*den+i)==Fraction(num, den):
                print num, den
                frac_list.append(Fraction(num, den))

def findAlt(num, den):
    global prod
    for i in xrange(1, 10):
        if i == num or i == den:
            continue

        elif Fraction(10*num+i, 10*i+den)==Fraction(num, den):
            frac_list.append(Fraction(num, den))

        elif Fraction(10*i+num, 10*den+i)==Fraction(num, den):
            frac_list.append(Fraction(num, den))

for i in xrange(1, 10):
    for j in xrange(1, 10):
        if i==j:
            continue
        else:
            findLeft(i, j)
            findRight(i, j)
            findAlt(i, j)

prod = 1
for i in xrange(len(frac_list)):
    if frac_list[i] < 1/1:
        prod *= frac_list[i]

print prod

BTW, it is funny how total nutjobs with no clue about probes, payloads, science or physics take up the job of reporting the Chandrayaan’s progress.

Peace…..


About this entry