Maximize Number of Nice Divisors Problem
Description
LeetCode Problem 1808.
You are given a positive integer primeFactors. You are asked to construct a positive integer n that satisfies the following conditions:
- The number of prime factors of
n(not necessarily distinct) is at mostprimeFactors. - The number of nice divisors of
nis maximized. Note that a divisor ofnis nice if it is divisible by every prime factor ofn. For example, ifn = 12, then its prime factors are[2,2,3], then6and12are nice divisors, while3and4are not.
Return the number of nice divisors of n. Since that number can be too large, return it modulo 10^9 + 7.
Note that a prime number is a natural number greater than 1 that is not a product of two smaller natural numbers. The prime factors of a number n is a list of prime numbers such that their product equals n.
Example 1:
Input: primeFactors = 5
Output: 6
Explanation: 200 is a valid value of n.
It has 5 prime factors: [2,2,2,5,5], and it has 6 nice divisors: [10,20,40,50,100,200].
There is not other value of n that has at most 5 prime factors and more nice divisors.
Example 2:
Input: primeFactors = 8
Output: 18
Constraints:
1 <= primeFactors <= 10^9
Solution
Approach: Split Into Threes + Fast Power
Write n = p1^k1 * p2^k2 * ... * pm^km. A nice divisor must contain every prime at least once, so it can pick any exponent from 1 to ki for each prime, giving k1 * k2 * ... * km nice divisors. The number of prime factors is k1 + k2 + ... + km, which may be at most primeFactors.
So the task becomes: split the integer primeFactors into positive parts so that their product is as large as possible. The classic answer is to use as many 3s as possible:
- If
primeFactors < 4, the answer isprimeFactorsitself. - If
primeFactors % 3 == 0, the answer is3^(primeFactors / 3). - If
primeFactors % 3 == 1, replace one3 + 1by2 + 2: the answer is4 * 3^(primeFactors / 3 - 1). - If
primeFactors % 3 == 2, the answer is2 * 3^(primeFactors / 3).
The powers are computed with fast exponentiation modulo 10^9 + 7.
Complexity: O(log n) time and O(1) extra space, where n is primeFactors.
class Solution:
def maxNiceDivisors(self, primeFactors: int) -> int:
mod = 10**9 + 7
if primeFactors < 4:
return primeFactors
if primeFactors % 3 == 0:
return pow(3, primeFactors // 3, mod) % mod
if primeFactors % 3 == 1:
return 4 * pow(3, primeFactors // 3 - 1, mod) % mod
return 2 * pow(3, primeFactors // 3, mod) % mod