Reputation: 163
I recently came across this question in a hiring challenge :
Given an interval [L, R] (1 <= L,R <= 10^5), we need to tell number of coprimes of K in interval [L, R] for each K in [L, R].
e.g. L = 3, R = 7
for K = 3, number of coprimes in [3, 7] = 3 (4, 5, 7)
for K = 4, number of coprimes in [3, 7] = 3 (3, 5, 7)
for K = 5, number of coprimes in [3, 7] = 4 (3, 4, 6, 7)
...
By my approach, I am finding prime numbers upto R and then for each K, by its prime factors, counting number of coprimes, but I need better and efficient approach than this. Thanks in advance.
Upvotes: 4
Views: 654
Reputation: 3038
One approach would be the following.
For every number K perform the following steps:
Remark: in step 2 we can similarly use the inclusion-exclusion principle to directly count the numbers which are co-prime with K (however, it feels more natural to me to count the multiples of numbers in set D). This would not require step 3 anymore.
Upvotes: 4