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

Counting Fractions

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 d≤8d \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, \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 2121 elements in this set.

How many elements would be contained in the set of reduced proper fractions for d≤1 000 000d \le 1\,000\,000?

View on Project Euler

Implementations

cpp
#include <iostream>
#include <vector>
long long counting_fractions()
{
const int MAXN = 1000000;
std::vector<long long> phi(MAXN+1);
for(int i=0; i<=MAXN; i++) phi[i] = i;
for(int i=2; i<=MAXN; i++){
if(phi[i] == i){ // prime
for(long long j=i; j<=MAXN; j+=i){
phi[j] = phi[j] / i * (i-1);
}
}
}
long long sum = 0;
for(int i=2; i<=MAXN; i++){
sum += phi[i];
}
return sum;
}
#if ! defined UNITTEST_MODE
int main(int argc, char const *argv[])
{
std::cout << "Answer: " << counting_fractions() << std::endl;
}
#endif // #if ! defined UNITTEST_MODE
View on GitHub
O(N log log N) time, O(N) space (totient sieve with summation)
tvarley.github.io/src/content/euler/problem-072.md

Problem #72 is taken from Project Euler and licensed under CC BY-NC-SA 4.0.