If you encounter a problem in the past two days, a range of [1 .. n], and any number M (1 <m <= N), count the number of natural numbers in the given domain and M.
We know that the necessary condition for determining the mutual quality of two numbers is that the maximum number of two numbers is 1. In this way, we only need to enumerate I (1 <= I <= N) and calculate GCD (I, m,
The time complexity of gcd (I, m) is logm + Logi. In addition to the enumeration time, the complexity is N * logm + logn!
If the problem is solved only once M, almost linear time, it is a good solution. However, if the value is m, for example, in [1... n], K number is selected.
The number is in [1 .. n], the complexity of the problem becomes O (K * n). If n = 50000, K = 10000 (that is, select one of the five numbers ), time close to count
Ten seconds, which is intolerable.
In addition, the number res of the number of non-reciprocal elements with m in [1. N] is obtained quickly, then n-res...
Fee theorem: If integer I and m are not mutually exclusive, at least one of all qualitative factors of M is also a qualitative factor of I.
Step 1: break down M for its quality factor
Method: Enumerate [2 .. SQRT (m')] and try to remove M'. Here m' is the initial value of M. Each time a prime factor is enumerated, all the factors in m' are removed,
Therefore, the average time is much smaller than SQRT (M), but in the worst case, SQRT (m) is still used, so we can optimize it and pre-process [1 .. n] EPO number table (n = 50000, prime number about 5000 ),
Calculate the time O (3 * n) of the prime number table by using the factorial method, and then use the generated prime number to try division.
Step 2: calculate the number of non-Mutual Quality
Assuming that the prime factor is P [PCNT] After M decomposition, the number of these prime factors in [1... n] is:
Formula: If PCNT = 3
N/P [1] + N/P [2] + N/P [3]-N/(P [1] * P [2]) -N/(P [1] * P [3])-N/(P [2] * P [3]) + N/(P [1] * P [2] * P [3])
I forgot what this is called. It seems like an extension of the Pigeon nest theorem.
In fact, the PCNT value is very small. If n = 50000, PCNT <7, because 2*3*5*7*11*13*17> 50000
In this way, we can perform a simple and in-depth search and calculate the value of the above formula. The DFS time PCNT * 2 ^ PCNT (= 384, n = 50000)
In this case, the total time is O (K * t) t = SQRT (m) + PCNT * 2 ^ PCNT (T <600, n = 50000), which is almost n independent,
Therefore, even if n = 50000, K = 10000, the computing complexity does not exceed 10 ^ 7, within 1 s, in fact, the local operation, but dozens of Ms.
So far, the problem has been solved, from dozens of S to dozens of Ms.
There should be better algorithms, and we look forward to thinking about it... Now, the content of the article is somewhat different from the question, hehe