Skip to content

Commit 4605ea0

Browse files
authored
Create maximize-number-of-nice-divisors.cpp
1 parent b56ef7d commit 4605ea0

File tree

1 file changed

+38
-0
lines changed

1 file changed

+38
-0
lines changed
Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
// Time: O(logn)
2+
// Space: O(1)
3+
4+
// variant of "343. integer break"
5+
class Solution {
6+
public:
7+
int maxNiceDivisors(int primeFactors) {
8+
static const int mod = 1e9 + 7;
9+
10+
// given a1 + a2 + ... + ak <= n, find max of a1 * a2 * ... * ak
11+
// => given a1 + a2 + ... + ak <= n, find max of a1 * a2 * ... * ak
12+
// => ai is either 3 or 2, see proof in "343. integer break"
13+
if (primeFactors <= 3) {
14+
return primeFactors;
15+
}
16+
if (primeFactors % 3 == 0) {
17+
return powmod(3, primeFactors / 3, mod); // 6 => 3 * 3
18+
}
19+
if (primeFactors % 3 == 1) {
20+
return 4 * powmod(3, (primeFactors - 4) / 3, mod) % mod; // 4 => 2 * 2
21+
}
22+
return 2 * powmod(3, (primeFactors - 2) / 3, mod) % mod; // 5 => 2 * 3
23+
}
24+
25+
private:
26+
uint32_t powmod(uint32_t a, uint32_t b, uint32_t mod) {
27+
a %= mod;
28+
uint64_t result = 1;
29+
while (b) {
30+
if (b & 1) {
31+
result = result * a % mod;
32+
}
33+
a = uint64_t(a) * a % mod;
34+
b >>= 1;
35+
}
36+
return result;
37+
}
38+
};

0 commit comments

Comments
 (0)