Problem Euler #71
19 Febbraio 2013
Consider the fraction, n/d, where n and d are positive integers. If n<d and HCF(n,d)=1, it is called a reduced proper fraction. If we list the set of reduced proper fractions for d <= 8 in ascending order of size, we get: 1/8, 1/7, 1/6, 1/5, 1/4, 2/7, 1/3, 3/8, 2/5, 3/7, 1/2, 4/7, 3/5, 5/8, 2/3, 5/7, 3/4, 4/5, 5/6, 6/7, 7/8 It can be seen that 2/5 is the fraction immediately to the left of 3/7. By listing the set of reduced proper fractions for d <= 1,000,000 in ascending order of size, find the numerator of the fraction immediately to the left of 3/7.
Analisi:
Sicuramente per avere un risultato della frazione tendente a 3/7, dovremo
partire comunque dal numero più grande al denominatore, cioè 10^6, dopodichè
trovare quel numeratore per il quale si abbia come risultato una frazione minore
di 3/7. Appena trovata la coppia di numeri con risultato minore e molto vicino a
3/7, controlleremo anche che soddisfi la condizione di avere gcd = 1 (maggiore
comune divisore).
python:
import time from fractions import gcd from fractions import Fraction as f st = time.time() def euler_71(limit): rate = round(float(3)/7, 6) for d in xrange(limit, 1, -1): # descending for n in xrange(limit/2, 1, -1): # descending if round(float(n)/d, 6) < rate: fract = f(n, d) if gcd(fract.numerator, fract.denominator) == 1: return n print euler_71(1000000) print time.time() - st
In realtà esiste una soluzione molto più snella, terribilmente semplice:
3/7 = 0.428571
rappresentabile come:
428571/1000000
qual’è quella frazione, appena inferiore alla precedente e quindi prossima a 3/7?
Ecco appunto:
428570/1000000
vediamo se come gcd ci siamo?
python:
>>> from fractions import gcd >>> from fractions import Fraction as f >>> fr = f(428570, 1000000) >>> gcd(fr.numerator, fr.denominator) 1
bingo!
Quindi un sciocca soluzione one-line, potrebbe essere:
>>> (round(float(3)/7, 6)*10**6)-1 428570.0
Categorie:Project Euler, python
Commenti recenti