How to optimize a factor counting algorithm
I've been asked to sum the factors other than 1 and the number itself of
every number in an array. The problem is it must be able to handle very
large arrays with very large numbers and my current implementation takes
very long for arrays of size 100,000,000. My code for counting each
numbers factors is
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;
}
Does anybody have any optimisation suggestions.
No comments:
Post a Comment