Problem #73 hard
Counting Fractions in a Range
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 there are fractions between and .
How many fractions lie between and in the sorted set of reduced proper fractions for ?
Implementations
#include <iostream>#include <numeric>
int counting_fractions_range(){ int count = 0; for(int d=1; d<=12000; d++){ int n_min = d / 3 + 1; int n_max = (d - 1) / 2; for(int n=n_min; n<=n_max; n++){ if(std::gcd(n, d) == 1){ count++; } } } return count;}
#if ! defined UNITTEST_MODEint main(int argc, char const *argv[]){ std::cout << "Answer: " << counting_fractions_range() << std::endl;}#endif // #if ! defined UNITTEST_MODE View on GitHub
O(N^2) time, O(1) space (brute force with GCD checks)