0

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.

4
  • Please SPLIT code into functions. make numDivisors(int x) that returns number of divisors of number x. It'll make it easier for you and everyone else. Also, what you want doesn't seem to be dynamic arrays, They're a different concept Commented Mar 30, 2014 at 17:35
  • calculate: What a wonderfully descriptive name. Commented Mar 30, 2014 at 17:38
  • It's really strange that int divisors[size][size]; and int divisorssize[size]; compiles. The copiler doesn't know the size of the array, and therefore doesn't know how much space in the memory it is necessary to allocate. The compiler shouldn't let you do that. Commented Mar 30, 2014 at 18:29
  • We're in the 21st century now Alex :) Commented Mar 30, 2014 at 20:59

1 Answer 1

2

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]; 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.