Consider the fraction, n/d, where n and d are positive integers. If n<d and HCF(n,d)=1, it is called a reduced proper fraction.
If we list the set of reduced proper fractions for d ≤ 8 in ascending order of size, we get:
1/8, 1/7, 1/6, 1/5, 1/4, 2/7, 1/3, 3/8, 2/5, 3/7, 1/2, 4/7, 3/5, 5/8, 2/3, 5/7, 3/4, 4/5, 5/6, 6/7, 7/8
It can be seen that there are 21 elements in this set.
How many elements would be contained in the set of reduced proper fractions for d ≤ 1,000,000?
This problem is relatively easy if problem 70 is solved. The number of reduced proper fraction of d is equal to number less than d and is relatively prime to d. This can be calculated by the euler's totient function.
The *totient* function defined in problem 70, was used here to calculate φ(d).
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 | #include<iostream> #include<cmath> using namespace std; const int N = 1e6+1; int totient(int n); int main() { long int cnt=0; for (int d = 2; d < N; d++) { cnt += totient(d); } cout << "Answers to PE 72: " << cnt << endl; } int totient(int n) { static int phis[N] = {0, 1, 1}; if (phis[n] != 0) { return(phis[n]); } for (int p=2; p <= sqrt(n); p++) { if ( n % p == 0 ) { int pk = p; while ( (n % (pk * p) == 0) ) { pk *= p; } if ( pk == n ) { // phis[n] = p^k phis[n] = n - n/p; return phis[n]; } if ( phis[pk] == 0 ) { phis[pk] = pk - pk/p; } phis[n] = totient(pk) * totient(n/pk); return phis[n]; } } phis[n] = n-1; return phis[n]; } |
Runs < 2 mins.
Answers to PE 72: 303963552391 user system elapsed 1.188 0.010 1.201