好因子的最大数目
难度:
标签:
题目描述
代码结果
运行时间: 28 ms, 内存: 16.1 MB
/*
* Problem: Given a positive integer 'primeFactors', you need to construct a positive integer 'n' that meets the following conditions:
* 1. The number of prime factors (considering repeated factors) of 'n' does not exceed 'primeFactors'.
* 2. The number of good factors of 'n' is maximized. A factor of 'n' is called a good factor if it can be divided by each prime factor of 'n'.
* The result should be returned modulo 10^9 + 7.
*
* Approach using Java Stream API: The problem can be approached in a similar way as traditional Java.
* We use streams for calculation where possible, especially in the modPow method.
*/
import java.util.stream.Stream;
public class Solution {
private static final int MOD = 1000000007;
public int maxGoodFactors(int primeFactors) {
if (primeFactors <= 3) return primeFactors;
long result = 1;
if (primeFactors % 3 == 0) {
result = modPow(3, primeFactors / 3);
} else if (primeFactors % 3 == 1) {
result = (modPow(3, primeFactors / 3 - 1) * 4) % MOD;
} else if (primeFactors % 3 == 2) {
result = (modPow(3, primeFactors / 3) * 2) % MOD;
}
return (int) result;
}
private long modPow(long base, int exp) {
return Stream.iterate(new long[]{1, base}, e -> new long[]{
e[1] * e[1] % MOD, e[0] * ((exp & 1) == 1 ? e[1] : 1) % MOD
})
.limit(exp + 1)
.map(e -> e[0])
.reduce((a, b) -> b)
.get();
}
}
解释
方法:
题解基于分解质因数的方式来最大化好因子数目。通过分析可以发现,将整数n分解为多个3的乘积时,可以得到更多的好因子。具体策略为:1. 当primeFactors小于或等于3时,直接返回primeFactors,因为无法形成更多的好因子。2. 当primeFactors大于3时,首先计算将primeFactors尽可能多地分为3的组合,计算剩余的质因数数目。如果剩余1个,最优策略是使用一个2和两个3组成的数(即2*3*3),如果剩余2个,使用两个2更优(即2*2*3)。使用快速幂算法来高效计算大数的乘积的模。
时间复杂度:
O(log n)
空间复杂度:
O(1)
代码细节讲解
🦆
为什么选择3的乘积可以得到更多的好因子?请解释这种策略背后的数学原理。
▷🦆
题解中提到,当剩余的质因数为1时,使用一个2和两个3组成的数(即2*3*3)更优,为什么不直接使用3个3(即3*3*3)而选择减少一个3增加一个2?
▷🦆
快速幂算法在计算时为何优先考虑处理指数中的奇数情况,这样做的优点是什么?
▷