can someone help me put prime numbers into an array

array cannot have more than the number of primes between 0-50000
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
  #include <iostream>
#include <vector>
#include <fstream>
#include <cmath>

using namespace std;

int primecheck(long n);
void printprimes(int a, int size);

int main()
{
	int counter = 0;
	
	for(int i = 0; i <= 50000; i++)
	{
		if(primecheck(i))
		{
			counter++;
		}
	}

    int primearr[counter];
	printprimes(primearr, counter); // error here invalid conversion from int* to int
		
	return 0;
}
int primecheck(long n)
{
	for(int i = 2; i <= sqrt(n); i++)
    {
        if ((n%i) == 0)
        {
        	return 0;
		}
    }
    return 1;
}

void printprimes(int a, int size)
{
	for(int i = 0; i < 50000;i++)
	{
		if(primecheck(i))
		{
			a[i] = i;
		}
	}
	
	for(int i = 0; i < size; i++)
	{
		cout << a[i] << " ";
	}
}
why not use a vector outright (you've already included the header file for it) and push_back into this vector every prime found?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
array sizes must be known at compile time.  
int primearr[counter];  //can't do it in standard c++

int primearr[25000] = {0}; //we know at most 1/2 are prime. Its more like 10%, if I remember the rule of thumb, so 10k is probably overkill. 

for(int i = 0; i <= 50000; i++)
	{
		if(primecheck(i))
		{
                        primearr[counter++] = i;  //populate the array
			//counter++;  moved into above line
		}
	}




you can do a vector and grow it as you go, with push back, and preallocate it to your best guess. You can allocate a pointer to a run-time value size, but reallocating them is ugly. vector is the correct solution for unknown sized arrays, but you may not have seen them yet.
Last edited on
OP: if you have to use C-style arrays as part of your assignment you'd need a dynamic array:
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
#include <iostream>

bool isPrime(long n)
{
    if (n == 1)return true;

    for (auto i = 2; i * i  <= n; ++i)
    {
        if(!(n%i))return false;
    }
    return true;
}

size_t primeCounter (long n)
{
    size_t counter{};
    for (auto i = 1; i < n; ++i)
    {
        if(isPrime(i))++counter;
    }
    return counter;
}
int main()
{
    std::cout << "Enter long \n";
    long n{};
    std::cin >> n; //input validation
    size_t * primeArray = new size_t[primeCounter(n)];

    size_t counter{};
    for (long i = 1; i < n; ++i)
    {
        if(isPrime(i))
        {
            primeArray[counter] = i;
            ++counter;
        }
    }
    for (size_t i = 0; i < primeCounter(n); ++i)
    {
        std::cout << primeArray[i] << "\n";
    }
    delete [] primeArray;
}
Topic archived. No new replies allowed.