Querying maximum number of divisors that a number in a given range has
Given Q queries, of type: L R, for each query you must print the maximum number of divisors that a number x (L <= x <= R) has.
L = 1 R = 10: 1 has 1 divisor. 2 has 2 divisors. 3 has 2 divisors. 4 has 3 divisors. 5 has 2 divisors. 6 has 4 divisors. 7 has 2 divisors. 8 has 4 divisors. 9 has 3 divisors. 10 has 4 divisors. So the answer for above query is 4, as it is the maximum number of divisors a number has in [1, 10].
- Firstly, let’s see how many number of divisors does a number n = p1k1 * p2k2 * … * pnkn (where p1, p2, …, pn are prime numbers) has; the answer is (k1 + 1)*(k2 + 1)*…*(kn + 1). How? For each prime number in the prime factorization, we can have its ki + 1 possible powers in a divisor (0, 1, 2,…, ki).
- Now let’s see how can we find the prime factorization of a number, we firstly build an array, smallest_prime, which stores the smallest prime divisor of i at ith index, we divide a number by its smallest prime divisor to obtain a new number (we also have the smallest prime divisor of this new number stored), we keep doing it until the smallest prime of the number changes, when the smallest prime factor of the new number is different from the previous number’s, we have ki for the ith prime number in the prime factorization of the given number.
- Finally, we obtain the number of divisors for all the numbers and store these in a segment tree that maintains the maximum numbers in the segments. We respond to each query by querying the segment tree.
Maximum divisors that a number has in [1, 100] are 12 Maximum divisors that a number has in [10, 48] are 10 Maximum divisors that a number has in [1, 10] are 4
For sieve: O(maxn * log(log(maxn)) ) For calculating divisors of each number: O(k1 + k2 + ... + kn) < O(log(maxn)) For querying each range: O(log(maxn)) Total: O((maxn + Q) * log(maxn))
This article is contributed by Saumye Malhotra. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.