Why run time error in the given code??


  • 0

  • 0
    A

    The url provided is not accessible.
    Besides my code here is also getting the same error (although it compiles and runs fine on my mac gcc) for the same input (here the input which failed is 6):

    // http://en.wikipedia.org/wiki/Sieve_of_Eratosthenes
    int countPrimes(int n) {
    int *arr, n2, i, j, k = 0;
    int count = 0;

    if (n <= 1) return 0;
    if (n <= 3 ) {
        return n-1;
    }
    
    arr = (int *)malloc(n * sizeof(int));
    
    for (i = 0 ; i < n ; i++) {
        arr[i] = i;
    }
    
    for (i = 2 ; i < n ; i++) {
        j = k = arr[i];
        if (arr[k] == 0) {
            continue;
        }
        while(k <= n) {
            if (arr[k] == 0) {
                k = k + j;
                continue;
            }
            if (k != j) arr[k] = 0;
            k = k + j;
        }
    }
    
    for (i = 2 ; i < n ; i++) {
        if (arr[i] != 0) count++;
    }
    
    free(arr);
    
    return count;
    

    }


Log in to reply
 

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