LeetCode 1808. Maximize Number of Nice Divisors

Math

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 most primeFactors.

  • The number of nice divisors of n is maximized. Note that a divisor of n is nice if it is divisible by every prime factor of n. For example, if n = 12, then its prime factors are [2,2,3], then 6 and 12 are nice divisors, while 3 and 4 are not.

Return the number of nice divisors of n. Since that number can be too large, return it modulo 109 + 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

English Version in Youtube

中文版解答Youtube Link

中文版解答Bilibili Link

class Solution {
    
    long mod = 1e9+7;
    
public:
    int maxNiceDivisors(int primeFactors) {
        int groups_of_3 = primeFactors/3;
        int groups_of_2 = 0;
        int remain = primeFactors - groups_of_3 * 3;
        if (remain == 1) {
            if (groups_of_3 > 0) {
                groups_of_3--;
                groups_of_2 = 2;
            }
        } else if (remain == 2) {
            groups_of_2 = 1;
        }
        
        long ans = 1;
        
        int num_3_used = 0;
        int limit = sqrt(primeFactors);
        int temp = 1;
        while (groups_of_3 > 0) {
            ans *= 3;
            ans %= mod;
            groups_of_3--;
            num_3_used++;
            if (num_3_used == limit) {
                temp = ans;
                break;
            }
        }
        while (groups_of_3 >= limit) {
            ans *= temp;
            ans %= mod;
            groups_of_3 -= limit;
        }
        while (groups_of_3 > 0) {
            ans *= 3;
            ans %= mod;
            groups_of_3--;
            num_3_used++;
        }
        
        while (groups_of_2 > 0) {
            ans *= 2;
            ans %= mod;
            groups_of_2--;
        }
        
        return ans;
    }
};

Last updated