I'm writing a program in which I want to find all abundant numbers until 28124. I can do it with a static array but I want to improve my code and adjust it with a dynamic way. Here is my code:
#define N 28124
bool is_abundant(int number)
{
int i;
int sum=0;
for(i=1;i<=number/2;i++)
{
if(number % i == 0)
sum += i;
if(sum > number) return true;
}
return false;
}
int main(int argc, char **argv)
{
clock_t start = clock();
int i, j=0;
int *abundants = NULL;
for(i=12;i<N;i++)
{
if(is_abundant(i))
{
abundants = (int*)malloc(sizeof(int));
assert(abundants);
abundants[j] = i;
j++;
}
}
for(i=0;i<j;i++)
{
printf("%d ", abundants[i]);
}
clock_t end = clock();
double time = (double) (end - start)/CLOCKS_PER_SEC;
printf("Execution time: %lf\n", time);
return 0;
}
The program aborts due to assert failure but how can I change it so as to works properly in a dynamic way?
You need to multiply sizeof(int)
by the number of ints you want to allocate. Otherwise you just allocate a single element.
You also need to use realloc()
so you grow the existing array rather than allocating a new array.
for(i=12;i<N;i++)
{
if(is_abundant(i))
{
abundants = realloc(abundants, (j+1) * sizeof(int));
assert(abundants);
abundants[j] = i;
j++;
}
}