0

我正在尝试做一个方法,它的函数名为 factor_count,它接受一个整数作为其参数并返回其正因子的计数。

比如32的六个因数分别是1、2、4、8、16、32,所以我的方法调用应该返回6。

int factor_count(int number) {
  int i, count;
  for (i=1;i<=number;i++){
    if(number%1==0){
      count = number%i;
    }
  }
  return count;
}
4

3 回答 3

1

%是模运算符。这是除法后的余数。如果除法后的余数为零,则应增加计数。除以 1 的余数始终为零。

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;
}
于 2018-02-12T21:23:39.410 回答
0

通常的解决方案是尝试除数:1,2,3,...,sqrt(n)。

每次迭代,注意除数余数

如果提醒为 0,则除数是一个因子。如果它的商大于除数,那么商也是一个新因素。

当除数小于商时继续循环。

迭代到sqrt(n)就足够了,而且比迭代到快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;
}

改进可以包括在每次找到除数时减少数量。以下内容未经过全面测试。

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;
}

factor_count2()进入下一个素数可以获得更多改进。

    // divisor++;
    divisor = next_prime(divisor);
于 2018-02-13T00:03:45.250 回答
0

请删除并用然后number%1==0替换它。在循环外初始化。number%i==0count = count + 1count = 0

于 2018-02-12T21:24:44.077 回答