0

The program is crashing each time I am compiling it.I need to find the 10001 th prime number. I know this is a case of stack overflow but could not solve it.Tell me the solution to the problem.

// program to find 10001th prime number. 
#include<stdio.h>
#define MAX 1000000
int main()
{
int primes[MAX];
int i,p,isprime;
primes[0]=2;
primes[1]=3;
int primeindex=2;


for(p=5;p<MAX;p=p+2)  //iterating over all the odd numbers
{  isprime=1;    // assuming that the number chosen is prime

    for(i=0;i<primeindex;i++)
    {
        if(p % primes[i]==0)
        isprime=0;
    }

    if(isprime ==1)
    { 
     primes[primeindex]=p;   //updating the list of prime numbers
     primeindex ++;     // updating the list of prime index
    }
   }
     printf("%d\n",primes[10000]); //supposed to print 10001 prime number   

     printf(" %d",primeindex);

   return 0;

  }
Rupesh
  • 19
  • 1
    Use pointer and allocate it memory . – ameyCU Apr 27 '16 at 18:13
  • 1
    Try making the array `static`. – Steve Summit Apr 27 '16 at 18:14
  • I have tried using static but that doesn't seems to work. – Rupesh Apr 27 '16 at 18:16
  • Are you saying the *compiler* is crashing when you try to build this? Or is your program crashing when you try to run it? Or is the compiler exiting with an error or warning? FWIW, I'm able to build this code on SLES 10 using gcc 4.1.2 with `-std=c11 -pedantic -Wall -Werror` and get no errors or warnings during compilation, and it doesn't crash when I run it. Granted, it's taking a while to run (O(n^2) algorithms tend to run slowly when n gets large), but it's not crashing. Here's a thought, though, try using `unsigned int` for `p` and `primeindex`. – John Bode Apr 27 '16 at 18:53

0 Answers0