Python Implementation of Problem 33

View source code here on GitHub!

Includes

Problem Solution

Project Euler Problem 33

This ended up being a filtering problem. The problem with my solution is that I am not satisfied with my filter at all. I feel like there is a more efficient way to go about it.

Problem:

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.

python.src.p0033.main() int
 1"""
 2Project Euler Problem 33
 3
 4This ended up being a filtering problem. The problem with my solution is that I
 5am not satisfied with my filter at all. I feel like there is a more efficient
 6way to go about it.
 7
 8Problem:
 9
10The fraction 49/98 is a curious fraction, as an inexperienced mathematician in
11attempting to simplify it may incorrectly believe that 49/98 = 4/8, which is
12correct, is obtained by cancelling the 9s.
13
14We shall consider fractions like, 30/50 = 3/5, to be trivial examples.
15
16There are exactly four non-trivial examples of this type of fraction, less
17than one in value, and containing two digits in the numerator and denominator.
18
19If the product of these four fractions is given in its lowest common terms,
20find the value of the denominator.
21"""
22from fractions import Fraction
23from itertools import combinations
24
25
26def main() -> int:
27    answer = Fraction(1, 1)
28    counter = 0
29    for num, denom in combinations(range(10, 100), 2):
30        frac = Fraction(num, denom)
31        if frac < 1:
32            rnum = repr(num)
33            rdenom = repr(denom)
34            if any(x in rdenom for x in rnum):
35                if not any(x == y for x, y in zip(rnum, rdenom)):
36                    if any(Fraction(int(rnum[x]), int(rdenom[y])) == frac
37                           for x, y in combinations(range(len(rnum)), 2)
38                           if rdenom[y] != "0"):
39                        answer *= frac
40                        counter += 1
41    return answer.denominator

Tags: fraction