Monday, September 13, 2010

Useful Algorithms/Methods




Returns true if candidate is a factor of number

boolean isFactor(int number, int candidate){
if (number % candidate == 0 )
return true;
else
return false;
}


Returns the sum of the factors of number that are less than the number

int sumOfFactorsBelowNumber(int number){
int result=0;
for (int candidate = 1; candidate < number/2; candidate = candidate+1){
if (isFactor(number,candidate))
result = result + candidate;
}
return result;
}



Returns the count of factors of n

int countFactors(int n) {
int count=0;
for (int x=1; x<=n; x++){
if (isFactor(n,x))
count = count + 1;
}

return count;
}



Returns the count of factors of n

int countFactorsVersion2(int n) {
int count=1;
for (int x=1; x<=n/2; x++){
if (n >1)
if (isFactor(n,x))
count = count + 1;
}

return count;
}



No comments:

Post a Comment