Sieve of Eratosthenes

Using the Sieve of Eratosthenes
algorithm, determine the prime numbers in [0, kN] as well as the number of primes and the max prime.

I've managed to get the prime numbers but I'm having issues getting the max. It keeps returning "1". If you can help me get the max prime number to print I'll be very grateful.


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
int main()
{
	int userInput, max = 0, count =0;
	cout << "Enter a number: ";
	cin >> userInput;
	vector<int> sieve(userInput + 1, true);
	sieve[0] = false;
	sieve[1] = false;

	int x = sqrt(userInput);
	for (int i = 2; i <= x; i++) {
		if (sieve[i]) {
			for (int j = 2 * i; j <= userInput; j += i) {
				sieve[j] = false;
			}
			if (sieve[i] > max) {
				max = sieve[i];
			}
		}
	}
	for (int i = 0; i <= userInput; i++) {
		if (sieve[i]) {
			cout << i << " ";

			count++;
			
		}

	}
	

	cout << endl;
	cout << "Number of Primes: "<< count << endl;
	cout << "Max is: " << max;
}
Last edited on
On lines 16 and 17: sieve[i] contains the primality of i. i is the number in question.
Also note that i will not reach past sqrt(userInput), but the sieve may contain some primes that are > sqrt(userInput) and <= userInput.
Last edited on
Thank you so much for your help. I've managed to get it to print the maximum prime number.
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
int main()
{
	int userInput, max = 0, count = 0;
	cout << "Enter a number: ";
	cin >> userInput;
	vector<int> sieve(userInput + 1, true);
	sieve[0] = false;
	sieve[1] = false;

	int x = sqrt(userInput);
	for (int i = 2; i <= x; i++) {
		if (sieve[i]) {
			for (int j = i * i; j <= userInput; j += i) {
				sieve[j] = false;
			}
		}
	}
	for (int i = 0; i <= userInput; i++) {
		if (sieve[i]) {
			cout << i << " ";
			max = i;

			count++;
			
		}

	}


	cout << endl;
	cout << "Number of Primes: "<< count << endl;
	cout << "Max is: " << max;
}
Last edited on
Topic archived. No new replies allowed.