LeetCode 1808: Maximize Number of Nice Divisors

Problem Description

Explanation

To maximize the number of nice divisors of n, we need to find the optimal distribution of prime factors. We can achieve this by using the fact that the product of the divisors should be maximized. We can calculate the optimal number of 2s and 3s in the prime factorization of n. If the total number of prime factors is odd, we can add an extra 3 to maximize the divisors. The formula for calculating the number of nice divisors is (2^a)(3^b)(5^c)*... where a, b, c, ... are the optimal numbers of prime factors.

Solutions

class Solution {
    public int maxNiceDivisors(int primeFactors) {
        if (primeFactors <= 3) return primeFactors;
        
        long result = 1;
        long mod = 1000000007;
        
        if (primeFactors % 3 == 0) {
            result = modPow(3, primeFactors / 3, mod);
        } else if (primeFactors % 3 == 1) {
            result = (4 * modPow(3, (primeFactors - 4) / 3, mod)) % mod;
        } else {
            result = (2 * modPow(3, (primeFactors - 2) / 3, mod)) % mod;
        }
        
        return (int) result;
    }
    
    private long modPow(long x, long n, long mod) {
        long result = 1;
        while (n > 0) {
            if (n % 2 == 1) {
                result = (result * x) % mod;
            }
            x = (x * x) % mod;
            n /= 2;
        }
        return result;
    }
}

Loading editor...