File tree Expand file tree Collapse file tree 1 file changed +38
-0
lines changed Expand file tree Collapse file tree 1 file changed +38
-0
lines changed Original file line number Diff line number Diff line change
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
+ };
You can’t perform that action at this time.
0 commit comments