我被要求将除 1 以外的因子和数组中每个数字的数字本身相加。问题是它必须能够处理具有非常大数字的非常大的数组,而我当前的实现对于大小为 100,000,000 的数组需要很长时间。我计算每个数字因素的代码是
static long countFactors(long num){
long count=0;
long max =(long) Math.floor(Math.sqrt(num));
for(int i=2; i<=max;i++){
if(num%i==0&&(i*i)!=num){
// count i and n/i as a factor
count+=2;
if(num/i<max){
max=num/i;
}
}
else if(num%i==0){
// just add one factor since it is the numbers root.
count+=1;
}
}
return count;
}
有没有人有任何优化建议。