- 2022-06-19:给出n个数字,你可以任选其中一些数字相乘,相乘之后得到的新数字x,
x的价值是x的不同质因子的数量。
返回所有选择数字的方案中,得到的x的价值之和。
来自携程。
/**
* 模型:返回质数列表
*
* @param num
* @return
*/
public static ArrayList<Long> primes(long num) {
ArrayList<Long> ans = new ArrayList<>();
for (long i = 2; i * i <= num && num > 1; i++) {
if (num % i == 0) {
ans.add(i);
while (num % i == 0) {
num /= i;
}
}
}
//自己本身
if (num != 1) {
ans.add(num);
}
return ans;
}
/**
* 模型:返回质因子的数量,包含其中的一些数字相乘
*
* @param arr
* @return
*/
public static long sumOfValues(int[] arr) {
//key:某个质数因子
//value: 有多少个数含有这个因子
HashMap<Long, Long> cntMap = new HashMap<>();
for (int num : arr) {
for (long factor : primes(num)) {
cntMap.put(factor, cntMap.getOrDefault(factor, 0L) + 1L);
}
}
int n = arr.length;
long ans = 0;
//cont: 含有这个因子的数,有多少个
//others: 不含有这个因子的数,有多少个
for (long count : cntMap.values()) {
long others = n - count;
ans += (power(2, count) - 1) * power(2, others);
}
return ans;
}
/**
* 模型:2的次方
*
* @param num
* @param n
* @return
*/
public static long power(long num, long n) {
if (n == 0L) {
return 1L;
}
long ans = 1L;
while (n > 0) {
if ((n & 1) != 0) {
ans *= num;
}
num *= num;
n >>= 1;
}
return ans;
}