# Project Euler Problem 71 Solution

## Question

Consider the fraction, $\frac{n}{d}$, where $n$ and $d$ are positive integers. If $n \lt d$ and $\mathrm{HCF}(n,d)=1$, it is called a reduced proper fraction.

If we list the set of reduced proper fractions for $d \leq 8$ in ascending order of size, we get:

$\displaystyle \frac{1}{8}, \frac{1}{7}, \frac{1}{6}, \frac{1}{5}, \frac{1}{4}, \frac{2}{7}, \frac{1}{3}, \frac{3}{8}, \frac{2}{5}, \frac{3}{7}, \frac{1}{2}, \frac{4}{7}, \frac{3}{5}, \frac{5}{8}, \frac{2}{3}, \frac{5}{7}, \frac{3}{4}, \frac{4}{5}, \frac{5}{6}, \frac{6}{7}, \frac{7}{8}$

It can be seen that $\frac{2}{5}$ is the fraction immediately to the left of $\frac{3}{7}$.

By listing the set of reduced proper fractions for $d \leq 1,000,000$ in ascending order of size, find the numerator of the fraction immediately to the left of $\frac{3}{7}$.

prevFrac :: Int -> Int -> Int -> (Int, Int)
prevFrac num den limit = inner 1 limit 1 where
inner n d i | i == limit = (n, d)
| den*m < num*i && m*d > n*i = inner m i (i+1)
| otherwise = inner n d (i+1)
where m = num*i quot den

main :: IO ()
main = print $fst$ prevFrac 3 7 1000000
$ghc -O2 -o ordered-fractions ordered-fractions.hs$ time ./ordered-fractions
real   0m0.012s
user   0m0.008s
sys    0m0.000s

## Python

#!/usr/bin/env python
from fractions import Fraction

def main():
three_sevenths = 3.0 / 7
closest = Fraction(three_sevenths).limit_denominator(1000000)
while closest == Fraction(3, 7):
three_sevenths -= 1e-6
closest = Fraction(three_sevenths).limit_denominator(1000000)
print(closest.numerator)

if __name__ == "__main__": main()
\$ time python3 prop-frac.py
real   0m0.030s
user   0m0.024s
sys    0m0.004s