Problem #72 hard
Counting 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 there are elements in this set.
How many elements would be contained in the set of reduced proper fractions for ?
Implementations
#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_MODEint 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)