Problem #71 easy
Ordered Fractions
Consider the fraction, , where and are positive integers. If and , it is called a reduced proper fraction.
If we list the set of reduced proper fractions for in ascending order of size, we get:
It can be seen that is the fraction immediately to the left of .
By listing the set of reduced proper fractions for in ascending order of size, find the numerator of the fraction immediately to the left of .
Implementations
#include <iostream>#include <numeric>
int ordered_fractions(){ long long best_n = 0, best_d = 1; for (int d = 1; d <= 1000000; ++d) { long long n = (3LL * d - 1) / 7; if (n > 0 && std::gcd((int)n, d) == 1) { if (best_n * (long long)d < n * best_d) { best_n = n; best_d = d; } } } return best_n;}
#if ! defined UNITTEST_MODEint main(int argc, char const *argv[]){ std::cout << "Answer: " << ordered_fractions() << std::endl;}#endif // #if ! defined UNITTEST_MODE View on GitHub
O(N) time, O(1) space (linear scan with GCD checks)