Problem euler #33
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.
Analisi:
1 – Numeratore e denominatore devono avere 2 cifre
2 – Numeratore e denominatore non devono contenere lo ‘0’
Nota punto 2:
In realtà le frazioni dovrebbero cadere nel caso ‘trivial’ (es.30/50)
quindi quando sia numeratore che denominatore hanno lo 0 finale.
In realtà possiamo considerare anche il singolo caso es.
20/32: eliminato il 2 avremmo 0/2 che dà come risultato 0 != da 20/32
23/30: eliminato il 3 avremmo 2/0 che non è possibile
3 – Il numeratore deve essere minore del denominatore per avere
risultato < 1
4 - i risultati delle frazioni e delle risultanti frazioni troncate,
devono essere uguali.
Ottenute le coppie (numeratore, denominatore) le semplifico al minimo
termine: es 49/98 = 1/2. Infine moltiplico i denominatori.
Ne consegue che:
Python:
[sourcecode lang="python"]
import time
ts = time.time()
def has_common_digit(n, m):
for d in str(n):
for dd in str(m):
if d == dd:
return True
return False
def check_fraction(num, den):
f_a = float(num)/float(den)
for d in str(num):
if d in str(den):
num = str(num).replace(d, '', 1)
den = str(den).replace(d, '';, 1)
break
f_b = float(int(num))/float(int(den))
if f_a == f_b: return True
return False
prod = 1
for num in range(11, 98): # scarto il 10 subito
for den in range(num + 1 , 99): # den > num
if num % 10 == 0 or den % 10 == 0: # scarto i mod 10
continue
else:
if has_common_digit(num, den): # controllo che abbiano
# una cifra in comune
if check_fraction(num, den): # controllo ugualianza frazioni
prod *= float(den)/num # riduco ad 1 il numeratore
print int(prod)
print time.time() - ts[/sourcecode]
Commenti recenti