我正在尝试编写一个程序,以检查具有360的第五个数字是否包含其总和。
我编写了一个程序,该程序获取用户输入的数字,并打印出因素,然后打印所有因素的总和。我遇到的困难是有两个计数变量(正在检查因子的数字和被除数的数字)。
这是我所拥有的:
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);
}
答案 0 :(得分:1)
带有描述变量的可配置示例:
#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
答案 1 :(得分:0)
对此稍加思考,得出的结论是360是必须测试的数字的合理上限。
足够有趣:359是质数,只有两个因子(1、359),总计为360(似乎是最高的候选项)。
因此,OP的代码可以包装到1 ... 360的循环中以解决此难题(以蛮力找到答案)。
我的示例代码:
#include <stdio.h>
int getSumFactors(int n)
{
int sum = 1 + n;
for (int i = 2; i < n; ++i) if (n % i == 0) sum += i;
return sum;
}
int main()
{
int nF = 0;
for (int n = 1; n <= 360; ++n) {
if (getSumFactors(n) == 360) printf("%d.: %d\n", ++nF, n);
}
printf("%d numbers with factors which sum up to 360.\n", nF);
return 0;
}
输出:
1.: 120
2.: 174
3.: 184
4.: 190
5.: 267
6.: 295
7.: 319
8.: 323
9.: 359
9 numbers with factors which sum up to 360.
我只有9个候选人–期望更多,这让我有些惊讶。 (关于我的“数学感觉” ...)