Cannot use dynamic memory? (C)


  • 0
    S
    int countPrimes(int n) {
        
        int retval = 0;
        int *list = calloc(n, sizeof(int));
        
        for (int i = 2; i < n; ++i) {
            for (int j = 2; j * i < n; ++j) {
                ++list[j * i];
            }
        }
        for (int k = 2; k < n; ++k) {
            if (list[k] == 0) ++retval;
        }
        free(list);
        return retval;
    }
    

    Submission Result: Memory Limit Exceeded.
    Could someone provide some help on my code?
    Thanks a lot!


  • 0
    R

    'Memory Limit Exceeded' means that U used too much memory. it has nothing to do with whether dynamic memory could be used.


    U can use the type of bool.like below

    bool *list = calloc(n, sizeof(bool));

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.