Using function to store prime number vectors.

I was attempting to store prime numbers in vectors while using a counter.
This code does nothing though. Is there a way to do this with the tools
I'm doing? Was I at least close to the goal?

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
// Test number 1-100 for primes.
#include<iostream>
#include<string>
#include<vector>
#include<algorithm>
#include<cmath>
using namespace std;
inline void keep_window_open(){char ch; cin>>ch;}

int prime (int x){

vector<int>primes;
primes[0] = 2;
primes[1] = 3;
primes[3] = 5;

for (int i = -1; i > primes.size(); ++i){
	if(x % primes[i] > 0){
		primes.push_back(x);
		cout << x << " is prime" << endl;
		}
	}
}

int main() { 

int counter = 6;

while (counter > 100){
	++counter;
	prime(counter);
	}
}
Last edited on

Each time prime is called, the previous result is lost, so you will only ever be dividing by 2, 3 and 5.

In the first place, what is the size of primes? Instead of guessing and doing potentially unsafe primes[0] = 2; use push_back:
1
2
3
primes.push_back(2);
primes.push_back(3);
primes.push_back(5);


loop indexing starts from i = -1, there is no primes[-1]

loop indexing continues until i > primes.size(), that is at least 2 positions too far

The test for primes is flawed, you'll end up adding the same number to the vector multiple times, each time you get a remainder. You should see if it ever divides cleanly and then add it once at the end of the loop if it doesn't.

There's no value returned from prime

Finally, in main, you initialise counter = 6, then start a loop while (counter > 100), this is immediately false, and your loop will never run. Looks like you mixed up less than (<) with greater than (>) twice (line 17 and line 29).

See the example below:

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
// Test number 1-100 for primes.
#include<iostream>
#include<vector>

using namespace std;

void prime(vector<int> &primes, int x)
{
	bool is_prime = true;
	for (size_t i = 0; i < primes.size(); ++i)
	{
		if(x % primes[i] == 0)
		{
			is_prime = false;
			break;
		}
	}
	
	if (is_prime)
	{
		primes.push_back(x);
		cout << x << " is prime" << endl;
	}
}

int main() 
{ 

	vector<int>primes;
	primes.push_back(2);
	primes.push_back(3);
	primes.push_back(5);

	for (int counter = 6; counter < 100; ++counter)
	{
		prime(primes, counter);
	}
	
	cout << "Prime numbers between 1 and 100 are: " << endl;
	for (size_t counter = 0; counter < primes.size(); ++counter)
	{
		cout << primes[counter] << endl;
	}
	
	cin.get();
}


Topic archived. No new replies allowed.