首页 > 解决方案 > 因子总和程序

问题描述

我正在尝试编写一个程序来检查具有 360 的第 5 个数字是否具有其因子的总和。

我编写了一个程序,它获取用户输入的数字并打印因子,然后打印所有这些因子的总和。我遇到困难的部分是有两个计数变量(检查因子的数字和除以的数字)。

这是我所拥有的:

    int number, i, total = 0;

    printf("Enter a number: ");
    scanf("%i", &number);

    printf("The factors of %i are:\n", number);

    for (i = 1; i <= number; i++)
    {
        if (number % i == 0)
        {
            printf("%i\n", i);
            total += i;
        }

    }
    printf("The sum of all the factors of %i is %i\n", number, total);

return(0);

}

标签: calgorithm

解决方案


带有描述性变量的可配置示例:

#include <stdio.h>     
#include <stdlib.h>

#define NUM_EMPLOYEES (1000)

int main()
{
    int number_to_consider;
    int potential_factor;
    int factor_total = 0;
    int num_suitable_numbers_found = 0;
    int desired_factor_total = 360;
    int number_of_numbers_to_Find = 5;

    for(number_to_consider = 1; number_to_consider < 10*desired_factor_total; number_to_consider++)
    {
        factor_total = 0;
        for (potential_factor = 1; potential_factor <= number_to_consider; potential_factor++)
        {
            if ((number_to_consider % potential_factor) == 0)
            {
                factor_total += potential_factor;
            }
        }

        if (factor_total == desired_factor_total)
        {
            num_suitable_numbers_found++;
            printf("Found candidate %i : %i\n", num_suitable_numbers_found, number_to_consider);
        }

        if(num_suitable_numbers_found >= number_of_numbers_to_Find)
        {
            break;
        }
    }

    return(0);
}

输出:

Found candidate 1 : 120
Found candidate 2 : 174
Found candidate 3 : 184
Found candidate 4 : 190
Found candidate 5 : 267

推荐阅读