Only odd numbers are considered when using Eratosthenes, why still runtime error?


  • 0
    K

    My code is based on "Sieve of Eratosthenes". And I only consider odd numbers so all of the O(n) part becomes O(n / 2). But why still runtime error when n is large (1500000)?

    int countPrimes(int n) {
        if (n < 3) {
            return 0;
        }
        int flag[n + 1];
        int cnt = n >> 1;
        
        for (int i = 0; i < n; i += 2) {
            flag[i + 1] = 1;
        }
        
        for (int i = 3; n / i >= i; i += 2) {
            if (!flag[i]) {
                continue;
            }
            int tmp;
            for (int j = 3; (tmp = j * i) < n; j += 2) {
                if (flag[tmp] == 1) {
                    flag[tmp] = 0;
                    cnt--;
                }
            }
        }
        
        return cnt;
    }
    

Log in to reply
 

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