c - 因子总和程序
问题描述
我正在尝试编写一个程序来检查具有 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);
}
解决方案
带有描述性变量的可配置示例:
#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
推荐阅读
- javascript - 无法在 node.js 上接收正文数据
- python - 在 Python 中操作包含其他列表的列表
- c# - 我可以在 C# 中模板化 Func 吗?
- javascript - Prev/Next 循环遍历 li 类处于活动状态的列表
- python - 使用 pytube 和 tkinter 在画布中显示 youtube 视频的缩略图
- purescript - 为什么将 try 与 affjax 的 XHRError 结合使用会导致错误类型不匹配?
- swift - Placenote Swift - 加载同一张地图后位置错误
- android - 单个 ImageButton 上的多个可绘制对象
- python - 展开多列
- kubernetes - Kops 和 Terraform k8s 集群重新创建