Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Program to maximize number of nice divisors in Python
Given a number pf representing the number of prime factors, we need to construct a positive number n that maximizes the number of nice divisors. A divisor is considered "nice" when it is divisible by every prime factor of n.
Problem Requirements
The number of prime factors of n (may or may not be distinct) is at most pf
The number of nice divisors of n is maximized
Return the count of nice divisors modulo 109 + 7
For example, if pf = 5, we can construct n = 200 with prime factors [2,2,2,5,5]. Its nice divisors are [10,20,40,50,100,200], giving us 6 divisors.
Algorithm Approach
The key insight is to distribute the prime factors optimally. To maximize divisors, we should use as many factors of 3 as possible, since 3 produces more divisors than larger prime factors ?
If pf is divisible by 3: use all factors of 3
If pf mod 3 = 1: replace one 3 with two 2s (since 2×2 = 4 > 3)
If pf mod 3 = 2: add one factor of 2
Implementation
def solve(pf):
if pf == 1:
return 1
m = 10**9 + 7
q, r = divmod(pf, 3)
if r == 0:
return pow(3, q, m)
elif r == 1:
return pow(3, q-1, m) * 4 % m
else:
return pow(3, q, m) * 2 % m
# Test with example
pf = 5
result = solve(pf)
print(f"Number of nice divisors for pf={pf}: {result}")
Number of nice divisors for pf=5: 6
How It Works
For pf = 5:
q = 5 // 3 = 1, r = 5 % 3 = 2
Since r = 2, we return 31 × 2 = 6
This corresponds to using one factor of 3 and one factor of 2
Test Cases
def solve(pf):
if pf == 1:
return 1
m = 10**9 + 7
q, r = divmod(pf, 3)
if r == 0:
return pow(3, q, m)
elif r == 1:
return pow(3, q-1, m) * 4 % m
else:
return pow(3, q, m) * 2 % m
# Test multiple cases
test_cases = [1, 3, 4, 5, 6]
for pf in test_cases:
result = solve(pf)
print(f"pf = {pf}: {result}")
pf = 1: 1 pf = 3: 3 pf = 4: 4 pf = 5: 6 pf = 6: 9
Conclusion
The algorithm maximizes nice divisors by optimally distributing prime factors, primarily using factors of 3. The time complexity is O(log q) due to the modular exponentiation, making it efficient even for large inputs.
