返回没有数字余数的除法器数之和的函数,C

时间:2015-12-04 21:07:03

标签: c function loops modulus divide

我可以轻松地在循环中打印我想要的内容,但我是新手的功能,我需要保存或返回没有余数的分频器之和到用户输入的数字。

示例:

输入 - 6

输出 - 1+2+3=6

我是如何开始的:

int NumberOfDividers(int number)
{
    int i,num, count = 0;
    num = number;
    for ( i = 0; i < num; i++)
    {
        if ((num % i) == 0) //so now I know i is one of the dividers i want to save.

    }
}

所以如果i是我想要的分隔符之一,我怎么能把它保存到变量中?还是数组?

4 个答案:

答案 0 :(得分:3)

要返回适当除数的总和,请执行:

int sum_of_proper_divisors (int number)
{
    int sum = 0;
    int i;
    for (i = 1; i < number; i++)
    {
        if ((number % i) == 0) 
           sum += i;
    }
    return sum;
}

您只需使用return关键字返回值。

答案 1 :(得分:2)

由于这项任务看起来很有趣,所以不想带走编码经验。而是制定了一个样本算法,该算法应该直接在C中编码。

伪代码

int *NumberOfDividers(int number)
  find isqrt(number) --> sqrt_number
  sqrt_number*2 + 2 --> max_array_count
  allocate int[] with max_array_count elements
  validate allocation
  starting at divisor = 1, in a loop ...
    quotient = number/divisor
    remainder = number%divisor
    if (remainder == 0)
      add divisor to list
      if (divisor != quotient) add quotient to list
    if (divisor >= quotient) quit loop
    divisor++
  append 0 to list to indicate the end
  shrink array to needed size if desired
  validate shrink result
  return array pointer.

注意循环最多执行sqrt(number)次迭代,因此在使用任何除数之前,可以计算所需数组大小的合理上限。

另请参阅How many positive integers are factors of a given number?了解更多高级创意。

答案 2 :(得分:2)

你可以这样做......

//other headers as you need
#include<string.h>//this header is for memset
int dividers[1000];//global array
int currPos;//global variable
int NumberOfDividers(int number)
{

   int i,num, count = 0;
   num = number;
   for ( i = 1; i < num; i++)//you should start counting from 1 otherwise you will get floating point exception
   {
       if ((num % i) == 0)
       {
           dividers[currPos]=i;//putting the dividers in the array
           currPos++;//updating the pivot where the next dividers will stay
       }
   }
   return 0;
}

int main()
{
    memset(dividers,0,sizeof(dividers));//initializing the array
    currPos=0;//initializing the variable to point at the start of the array
    NumberOfDividers(6);
    int i;
    int sum=0;
    for(i=0;i<currPos;i++)
    {
       printf("%d",dividers[i]);
       sum+=dividers[i];
       if(i!=currPos-1)
       {
           printf("+");
       }
   }
   printf("=%d\n",sum);
   return 0;
 }

答案 3 :(得分:0)

您可以看到另一种方法。对于大量数据,这将非常快速地工作。这是我的方式,你可以按照这个来找到这个以最快的方式找到一个数字因子的总和。这是我的代码:

int number_of_divisor(int n)
{
    int sum_of_factors=0;
    sum_of_factors+=1;//as 1 is factor of all num
    //sum_of_factors+=n;//n will always a factor of n

    for(int i = 2; i * i <= n; ++i)
    {
        if(n % i == 0)
        {
            sum_of_factors+=i;
            if(i * i != n)
                sum_of_factors+=(n/i);
        }
    }
    return sum_of_factors;
}

如果您的输入为long,则按int更改所有long

谢谢。