问题
I am trying to do a method that its function named is factor_count that accepts an integer as its parameter and returns a count of its positive factors.
For example, the six factors of 32 are 1, 2, 4, 8, 16, and 32, so the call of my method should return 6.
int factor_count(int number) {
int i, count;
for (i=1;i<=number;i++){
if(number%1==0){
count = number%i;
}
}
return count;
}
回答1:
%
is the modulo operator. It's remainder after a division. If the remainder after division is zero you should increment count. The remainder from dividing by 1 is always zero.
int factor_count(int number)
{
int i, count = 0;
for (i=1; i<=number; i++)
/* increment count when the remainder is zero */
if (number%i==0)
count++;
return count;
}
回答2:
Please remove number%1==0
and replace it with number%i==0
and
then count = count + 1
. Initialize count = 0
outside the loop.
回答3:
The usual solution is to try divisors: 1,2,3,...,sqrt(n).
Each iteration, note the divisor, quotient and remainder.
If the reminder is 0, then the divisor is a factor. If the quotient it is larger than the divisor, then the quotient is a new factor too.
Continue looping while the divisor is less than the quotient.
Iterating up to the sqrt(n)
is sufficient and faster than iterating up to n
int factor_count(int number) {
if (number <= 0) {
return TBD_Code(n); // OP needs to define functionality for these cases.
}
int count = 0;
int quotient;
int divisor = 0;
do {
divisor++;
quotient = number/divisor;
int remainder = number%divisor;
if (remainder == 0) {
count++;
if (quotient > divisor) count++;
}
} while (divisor < quotient);
return count;
}
Improvement can include reducing the number, each time a divisor is found. The following is not fully tested.
int factor_count2(int number) {
if (number <= 0) {
return TBD_Code(n); // OP needs to define functionality for these cases.
}
int count = 0;
int quotient;
int divisor = 0;
do {
divisor++;
int remainder;
do {
quotient = number/divisor;
remainder = number%divisor;
if (remainder == 0) {
number = quotient;
count++;
if (quotient > divisor) count++;
else break;
}
} while (remainder == 0);
} while (divisor < quotient);
return count;
}
Even more improvements can be had with factor_count2()
going to the next prime.
// divisor++;
divisor = next_prime(divisor);
来源:https://stackoverflow.com/questions/48755640/method-that-returns-count-of-its-positive-factors-in-c