Reputation: 3
I'm trying to write a program that checks for the 5th number that has 360 has the sum of its factors.
I wrote a program that gets a users entered number and prints the factors and then the sum of all those factors. The part I'm having difficulty with is having two counting variables (the number that is being checked for factors and the number that is being divided by).
Here is what I have:
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);
}
Upvotes: 0
Views: 14072
Reputation: 571
A configurable example with descriptive variables:
#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);
}
Output:
Found candidate 1 : 120
Found candidate 2 : 174
Found candidate 3 : 184
Found candidate 4 : 190
Found candidate 5 : 267
Upvotes: 1
Reputation: 20141
Thinking a little bit about this, I came to the conclusion that 360 is a reasonable upper boundary for numbers which have to be tested.
Funny, enough: 359 is a prime number and has only two factors (1, 359) which sum up to 360 (and seems to be the highest candidate).
Hence, the OP's code can be wrapped into a loop from 1 ... 360 to solve this puzzle (finding the answer with brute force).
My sample code:
#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;
}
Output:
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.
I'm a little bit surprised that there are only 9 candidates – had expected more. (So much about my "mathematical feeling"...)
Upvotes: 0