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.
C++ source code
#include <iostream>
using namespace std;
class PE0033
{
private:
int gcd(int a, int b);
bool checkDigitCancellingFraction(int a, int b, int c);
public:
int getValueOfDenominator();
};
int PE0033::gcd(int a, int b) // a < b
{
#ifdef UNIT_TEST
if(a < b)
{
int temp = a;
a = b;
b = temp;
}
#else
int r;
while(b != 0)
{
r = a%b;
a = b;
b = r;
}
#endif
return a;
}
bool PE0033::checkDigitCancellingFraction(int a, int b, int c)
{
// numerator(ab) = a*10+b
// denominator(bc) = b*10+c
// numerator/denominator = a/c => numerator*c = denominator*a
if ((a*10+b)*c == a*(b*10+c))
{
cout << a*10+b << "/" << b*10+c << " = " << a << "/" << c << endl;
return true;
}
return false;
}
int PE0033::getValueOfDenominator()
{
int a, b, c;
int product_numerator = 1;
int product_denominator = 1;
for (c=1; c<=9; c++)
{
for(a=1; a<c; a++)
{
for(b=1; b<=9; b++)
{
if (a == b)
{
continue;
}
if (true == checkDigitCancellingFraction(a, b, c))
{
product_numerator *= a;
product_denominator *= c;
}
}
}
}
int divisor = gcd(product_denominator, product_numerator);
return product_denominator/divisor;
}
int main()
{
PE0033 pe0033;
cout << "The value of the denominator is "<< pe0033.getValueOfDenominator()<<endl;
return 0;
}
Python source code
def gcd(a, b):
while( b != 0):
r = a % b
a, b = b, r
return a
def checkDigitCancellingFraction(a, b, c):
"""
numerator(ab) = a*10+b
denominator(bc) = b*10+c
numerator/denominator = a/c => numerator*c = denominator*a
=> (a*10+b)*c = (b*10+c)*a
"""
if (a*10+b)*c == (b*10+c)*a:
return True
else:
return False
def getValueOfDenominator():
product_numerator, product_denominator = 1, 1
for c in range(1, 10): # c: 1..9
for a in range(1, c): # a < c
for b in range(1, 10): # b: 1..9
if a == b:
continue
if True == checkDigitCancellingFraction(a, b, c):
product_numerator *= a
product_denominator *= c
divisor = gcd(product_numerator, product_denominator)
return int(product_denominator/divisor)
def main():
print("The value of the denominator is",getValueOfDenominator())
if __name__ == '__main__':
main()