Euler 0034
The Problem:
TheFind fractionthe 49/98sum isof aall curiousnumbers fraction, as an inexperienced mathematician in attemptingequal 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 examplessum of thistheir 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.factorials.
Considerations and Approach:
Naively... weWe can iterate through the denominator up to 100, and then iterate through the numerator up to the denominator.
To find the solutionupper welimit canby checkfilling everya number suchwith 9s and checking that the denominator and numerator have an equal digit, and that the resultsum of the fractiondigits is thegreater same asthan the digit reduced fractions.
We skip every multiple of 10 over 10 since numerator would make the reduced single digit fraction = 0, which won't ever be the casefactorial of the base fraction, or it will be undefined, which is problematic.We can start from 11 every time since we can't digit reduce a single digit number.
we find the upper limit, we increment through it and check each ones factorial, then take the sum of the digits.
The Code:
import math
#find the upper limit
digits = 9
sum_digits = math.factorial(9)
while sum_digits > digits:
digits *= 10
digits += 9
sum_digits += math.factorial(9)
print(len(str(digits)), digits, sum_digits)
### part 2 since we now know the upper limit
upper_limit = 1002540160
cycles = 0
non_trivial_denfact_nums = []
non_trivial_num = []
#denominator and numerator
for denominatori in range(11,100):3, for numerator in range(11,denominator)upper_limit):
if denominator % 10i == 0 or numerator % 10 == 0:
pass
else:
#iterate through the denominator to find numbers that are equivalent
counter = 0sum([math.factorial(int(x)) for den_indexx in range(len(str(denominator))i)]):
for num_index in range(len(str(numerator))):
cycles += 1
if int(str(numerator)[num_index]) == int(str(denominator)[den_index]):
new_num = int(str(numerator)[:num_index] + str(numerator)[(num_index+1):])
new_den = int(str(denominator)[:den_index] + str(denominator)[(den_index+1):])
if numerator/denominator == new_num/new_den:
print(denominator, numerator, new_num, new_den)
non_trivial_denfact_nums += [new_den]
non_trivial_num += [new_num]i]
print(cycles, math.prod(non_trivial_den), math.prod(non_trivial_num))fact_nums)