Question

So I am creating array and I need to find the number with highest divisors count, print the number, the count and divisors in decline order, if I create array with only 1 number my function works properly, but if I create it with 2 or more some divisors are changed into incorrect ones.

void calculate(int *data, int size){
    int max;
    int divisors[size][size];
    int divisorssize[size];
    //Checking for the divisors
  for (int i = 0; i < size; i++){
    divisorssize[i] = 0;
    for (int j = data[i]; j >= 1; j--) {
      if (data[i] % j == 0) {
        divisorssize[i]++;
        divisors[i][divisorssize[i]] = j;
      }
    }
  }
//Searching for the number in the array with the highest divisors count
  max = 0;
  for (int i = 0; i < size; i++){
    if (divisorssize[max] < divisorssize[i]){
      max = i;
    }
  }
//divisors Output
  printf("Max divisors: %d\n", data[max]);
  printf("divisors count: %d\n", divisorssize[max]);
  printf("divisors list: ");
  for (int i = 1; i <= divisorssize[max]; i++){
    printf("%d ", divisors[max][i]);
  }
}

Function usage :

calculate(data, size);

So when I create array with size = 1; And input number 56 it shows all divisors: 56 28 14 8 7 4 2 1, but if for example the size is 2 and I input 56 and 1, it changes the divisors into this 56 28 1 8 7 4 2 1.

Was it helpful?

Solution

The problem is with your array sizes.

For example, with size 2

int arr[size][size];

Will be

 int arr[2][2];

That is fine, as long as no number has more than two divisors...

The size of the second dimension needs to be big enough for any divisor count. For example, find the largest number in *data, and use that

 int array[size][max_number];
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top