Tim Varley Logo
Tim Varley Principal AI Engineer and Tech Leader
Problem #73 hard

Counting Fractions in a Range

Consider the fraction, nd\dfrac n d, where nn and dd are positive integers. If n<dn \lt d and HCF(n,d)=1\operatorname{HCF}(n, d)=1, it is called a reduced proper fraction.

If we list the set of reduced proper fractions for d8d \le 8 in ascending order of size, we get: 18,17,16,15,14,27,13,38,25,37,12,47,35,58,23,57,34,45,56,67,78\frac 1 8, \frac 1 7, \frac 1 6, \frac 1 5, \frac 1 4, \frac 2 7, \frac 1 3, \mathbf{\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 there are 33 fractions between 13\dfrac 1 3 and 12\dfrac 1 2.

How many fractions lie between 13\dfrac 1 3 and 12\dfrac 1 2 in the sorted set of reduced proper fractions for d12000d \le 12\,000?

View on Project Euler

Implementations

cpp
#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_MODE
int 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)
tvarley.github.io/src/content/euler/problem-073.md