Right now I am trying to solve Project Euler 71.
Consider the fraction, n/d, where n and d are positive integers. If
nIf 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/8It 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.
The Current Code:
from fractions import Fraction
import math
n = 428572
d = 1000000
x = Fraction(3,7)
best = Fraction(0)
while d > 1:
if Fraction(n,d) >= x:
n-=1
else:
y = Fraction(n,d)
if (x - y) < (x - best):
best = y
d -= 1
n = int(math.ceil(d*0.428572))
print(best.denominator)
Explanation:
from fractions import Fraction
import math
Needed for Fractions and math.ceil.
n = 428572
d = 1000000
These two variables represent the n and d stated in the original problem. The numbers start out this way because this is a slightly bigger representation of 3/7 (will be converted to Fraction later).
x = Fraction(3,7)
best = Fraction(0)
x is just a quick reference to Fraction(3,7) so I don’t have to keep typing it. best is used to keep track what fraction is closest to 3/7 but still left of it.
while d > 1:
If d <= 1 and n has to be less than 1 what is the point of checking? Stop check then.
if Fraction(n,d) >= x:
n-=1
If the fraction ends up being bigger than or equal to 3/7 it isn’t to the left of it, so keep subtracting from n till it is to the left of 3/7.
else:
y = Fraction(n,d)
if (x - y) < (x - best):
best = y
If it is to the left of 3/7 see if 3/7 minus best or y (which is equal to the fraction we need to check) is closer to 0. The one closer to zero will be the least left, or closest to 3/7.
d -= 1
n = int(math.ceil(d*0.428572))
Regardless of whether best changes or not, the denominator needs to be changed. So subtract one from the denominator and set n the Fraction(n,d) slightly greater (added extra ceil method to make sure it is greater!) than 3/7 to prune the test space.
print(best.denominator)
Finally print what the question wants.
Note
Changing d to 8 and n to 4 (like the test case) gives the desired result of 5 for the denominator. Keeping it as is gives: 999997.
Can someone please explain to me what I am doing wrong?
What you are doing wrong:
Apart from that, follow @Antimony’s advice and learn about the Stern-Brocot tree, that’s useful and fun.