Segmentation Fault.


  • 0
    B

    This is my code

    int precalculate(int* isprime){
            isprime[0]=0;
            isprime[1]=0;
            int i=2,j;
            for(i=2;i*i<=5000000;i++)
            {
                    if(isprime[i]==1)//if the number is crossed, it is skipped
                            continue;
                    for(j=i*2;j<=5000000;j+=i)// NOTE that j is incremented by i everytime
                    {
                            isprime[j]=1; // crossing every multiple of i
                    }
    
            }
            return 0;
    }
    
    int checkPrime(int* isprime,int n){
            if(isprime[n] == 1){
                    return 0;
            }
            return 1;
    }
    
    int countPrimes(int n) {
            int isprime[5000001]={0};
            precalculate(isprime);
            if(2 >= n){
                    return 0;
            }
            int i;
            int count = 0;
            for(i=2;i<n;i++){
                    if(checkPrime(isprime,i)){
                            count++;
                    }
            }
            return count;
    }
    

    I cannot understand why it is giving SEGFault.

    Please provide few inputs.


  • 0
    X

    int isprime[5000001]={0};
    5000001 is too large;


Log in to reply
 

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