How to get a result type n1 + n2 + n ... = x?

2

I'm learning C programming online and I wrote this code to find the perfect numbers in a given range, but I'd like to show the result with the sum of the divisors, for example:

1 + 2 + 3 = 6 PERFECT !!!
1 + 2 + 4 + 7 + 14 = 28 PERFECT !!!

My code looks like this:

#include <stdio.h>

int main(int argc, const char * argv[]) {

    int first_interval;
    int last_interval;
    int number;
    int divider;
    int sum = 0;

    printf ("Enter first and last interval's number\n");
    scanf("%d %d", &first_interval, &last_interval);

    for (number = first_interval; number >= first_interval && number <= last_interval; number++ ) {
        for (divider = 1; divider < number; divider++) {
            if (number % divider == 0) {
                sum = sum + divider;

            }

        }

        if (sum == number) {
            printf("%d = %d PERFECT !!!\n", number, sum);
        }

        sum = 0;

    }

    return 0;
}

How can I get the desired result, does anyone have any ideas?

    
asked by anonymous 16.03.2017 / 23:14

1 answer

2

A very simple way to do this is to store in an auxiliary vector the divisors of the number and, if it is perfect, to display them. The main limitation is that the number of divisors will be limited by the size of the vector.

#include <stdio.h>

int main(int argc, const char *argv[])
{

  int first_interval;
  int last_interval;
  int number;
  int divider;
  int sum = 0;

  // Define um vetor para armazer os divisores:
  int dividers[10] = {0};

  // Variável de controle para os divisores:
  int i = 0;

  printf("Enter first and last interval's number\n");
  scanf("%d %d", &first_interval, &last_interval);

  for (number = first_interval; number >= first_interval && number <= last_interval; number++ )
  { 
    for (divider = 1; divider < number; divider++)
    {
      if (number % divider == 0)
      {
        sum = sum + divider;

        // Encontrou um divisor, então armazena-o:
        dividers[i++] = divider;
      }
    }

    if (sum == number)
    {
      // Número é perfeito, então exibe os divisores:
      for (int j = 0; j < i-1; j++) printf("%d + ", dividers[j]);
      printf("%d = ", dividers[i-1]);

      printf("%d PERFECT !!!\n", number);
    }

    // Reinicia a variável de controle:
    i = 0;
    sum = 0;
  }

  return 0;
}
  

See working in the Ideone for the range between 1 and 500, the expected result is 6, 28, and 496.

The number 496 already has 9 divisors, so that's the maximum the program can get. The next number would be 8128, which has 14 divisors (more than the size of the vector).

You can work around this limitation by using dynamic memory allocation, but this is a future challenge for you, since (apparently) you're starting C studies now.

    
16.03.2017 / 23:42