mu chance or much chance ?

日々の戯れ言

Project Euler 33

  • 問題

Problem 33:Digit cancelling fractions
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.<<

  • 解答例
def gcd(m, n):
    while n:
        m, n = n, m % n
    return m

tempNumerator = 1
tempDenominator = 1
for a in range(1, 10):
    for b in range(1, 10):
        for c in range(1, 10):
            if a < b and not a == c and not b == c:
                if (10 * a + c) * b ==  (10 * c + b) * a:
                    temp1 = 10 * a + c
                    temp2 = 10 * c + b
                    tempNumerator *= temp1
                    tempDenominator *= temp2
                if (10 * c + a) * b ==  (10 * b + c) * a:
                    temp1 = 10 * c + a
                    temp2 = 10 * b + c
                    tempNumerator *= temp1
                    tempDenominator *= temp2

print(tempDenominator // gcd(tempNumerator, tempDenominator))