Prime numbers boolian stack overload.

I am trying to write a program to determine all prime numbers below an assigned value and it returns stack overload. The last part of my code is also telling if the number of primes is a prime number. Same for the number of lines of primes.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
  
#include <iostream>
#include <cmath>
#include <fstream>
using namespace std;

int main()
{
	ofstream myfile;
	myfile.open("prime.txt");

	const int jag=441181;
	int i,k,count,line;
	count=0;
	line=0;

	bool prime[jag+10];
	{
		for(i=2;i<jag+10;i++);
		{
			prime[i]=true;
		}
		for(i=2;i<sqrt(double(jag)+10);i++);
		{
			if(prime[i])
			{	
				for(k=i*i;k<jag+10;k+=i)
				prime[k]=false;
			}
		}
	for(i=2;i<jag+10;i++);
	{
		if(prime[i])
		{
			myfile<<i<<", ";
			count++;
			if(count%8==0)
			{
				cout<<endl;
				line++;
			}
		}
	}

	if(prime[count]) 
	{
		myfile<<"The number of primes before 441181 is also a prime value"<<endl;
	}
	if(prime[line])
	{
		myfile<<"The number of lines of primes before 441181 is also prime."<<endl;
	} 
	}
	myfile.close();
	return 0;
}
If you are finding the primes less than 441181 why are you adding ten instead of 1 (take into account the 0)? Also you may not have enough memory in the stack. Try creating it on the heap(pointer and new) or in the global space(above main). Another thing I would suggest is to use std::vector<bool> for prime sieves as it takes up about 1/8 the memory. Basically instead of the booleans being 1 byte each (8 bits) like a character they are used as 1 bit. Of course it has to reserve by bytes and not bits so if you have 1-7 it will still take up 8 bits/1byte. But instead of using 8 bytes for 8 booleans you are only using 1 byte. http://www.cplusplus.com/reference/vector/vector-bool/
Topic archived. No new replies allowed.