1

Attached is the code for finding all the primes between 2 numbers. t being the number of test cases and n, m are the upper and lower limit respectively. I ran this program and it keeps giving me sigsegv error.

#include <iostream>
using namespace std;
int Prime1(int n,int m)
{
    int i,j;
    //cout<<"Enter :"<<endl;
    //cin>>n;
    int x[n];
    for(i=0;i<=n;i++)
    {
        x[i]=1;
    }
    for(i=4;i<=n;i+=2)
    {
        x[i]=0;
    }
    for(i=3;i<=n;i+=2)
    {
        if(x[i])
        {
            for(j=2*i;j<=n;j+=i)
            {
                x[j]=0;
            }
        }
    }
    if(m==1)
    {
        m=m+1;}
        for(i=m;i<=n;i++)
        {
            if(x[i])
            {
                cout<<i<<endl;;
            }
        }

}
int main()
{
    int x,y,t;
    cin>>t;
    while(t!=0)
    {
        cin>>x>>y;
        cout<<endl;
        if(x>y)
        {
            Prime1(x,y);
        }
        else
        {
            Prime1(y,x);
        }
        t--;
    }
    system("pause");
}
johnsyweb
  • 136,902
  • 23
  • 188
  • 247
tortuga
  • 737
  • 2
  • 13
  • 34
  • You should have a look at the sieve of eratosthenes: http://stackoverflow.com/a/24185190/205521 – Thomas Ahle Jun 12 '14 at 13:15
  • possible duplicate of [How to find prime numbers between 0 - 100?](http://stackoverflow.com/questions/11966520/how-to-find-prime-numbers-between-0-100) – Thomas Ahle Jun 12 '14 at 13:20

3 Answers3

5

Look at these lines

int x[n];

for(i=0;i<=n;i++)

your array size is n, and you're trying to get value from n+1-th element

So it should be

int x[n];

for(i=0;i<n;i++)
Community
  • 1
  • 1
batbaatar
  • 5,448
  • 2
  • 20
  • 26
1

Here: int x[n];

You allocate memory for n ints, which goes up to index n-1. However in your for loops, you reference up to index n and thus causing the sigsegv. In general, sigsegv errors are a result of an invalid memory access.

For example, if your array is of size 3, you can only access x[0], x[1], and x[2]. Thus you either have to allocate n+1 elements or make your loop conditions i<n instead of i<=n. This will depend on your application logic.

tskuzzy
  • 35,812
  • 14
  • 73
  • 140
0

Hi, here is the code.


#include <iostream>

using namespace std;
void prime_num(int startNbr, int endNbr){

bool isPrime=true;

for ( int i = startNbr; i <= endNbr; i++) {

for ( int j = 2; j <= endNbr; j++){
if ( i!=j && i % j == 0 ){

isPrime=false;
break;
}
}

if (isPrime)
cout << i << endl;

isPrime=true;
}
}

int main(){
int startNbr, endNbr;

cout << " Enter start of the scale: ";
cin >> startNbr;

cout << " Enter end of the scale: ";
cin >> endNbr;

prime_num(startNbr, endNbr);

return 0;

}
ddacot
  • 1,212
  • 3
  • 14
  • 40