Sum of Multiples: Facing Error

#include "sum_of_multiples.h"
#include <stdlib.h>

unsigned int sum(const unsigned int *factors, const size_t number_of_factors,
                 const unsigned int limit)
{
    if (limit == 0) {
        return 0;
    }
    
    unsigned int res = 0;
    unsigned int* arr = NULL;
    
    if (limit > 0) {
        arr = malloc(limit * sizeof(unsigned int));
        if (arr == NULL) {
            // Memory allocation failed, return 0
            return 0;
        }
    }

    unsigned int i = 1, ind = 0; // Start from i = 1 to avoid 0 being included

    while (i < limit)
    {
        for (size_t k = 0; k < number_of_factors; k++) {
            if (i % factors[k] == 0)
            {
                arr[ind++] = i;
                break;  // We don't need to add the same number more than once
            }
        }
        i++;
    }

    // Summing up the elements
    for (unsigned int k = 0; k < ind; k++) {
        res = res + arr[k];
    }

    // Free the allocated memory
    free(arr);

    return res;
}

Not able to find the issue with the error, Working fine on other online IDEs. :

We received the following error when we ran your code:

make: *** [makefile:22: test] Arithmetic exception (core dumped)

If you had to guess, what could cause an “Arithmetic exception”?

Found out the issue and passed all test cases. Thank you for your inputs.

1 Like