Using c Create a program to find all the prime numbers betwe
Using c++
Create a program to find all the prime numbers between 2 and max. One way to do this is to is
as follows. Start with a vector called primes and push back 2 as it is prime. Then use a for loop
from 3 to max. With each iteration do the following:
1. Set a
flag is prime to true at the beginning of each iteration.
2. Use a for loop over the primes to see if the current value is divisible by any of the values in
the vector. If so, set the flag to false.
3. Depending on the flag, push back the current value into the vector of primes.
Write another loop that lists the primes you found. Here is a sample output:
Finding primes between 2 and max. Please enter the value for max:
200
The primes in [1, 200] are as follows:
primes = f2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67,
71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151,
157, 163, 167, 173, 179, 181, 191, 193, 197, 199g
Press ENTER or type command to continue
Solution
// C++ code find prime numbers between 2 and max
#include <iostream>
#include <string.h>
#include <fstream>
#include <limits.h>
#include <stdlib.h>
#include <math.h>
#include <iomanip>
#include <stdlib.h>
#include <vector>
using namespace std;
int main()
{
vector<int> primes;
int max;
cout << \"Enter max: \";
cin >> max;
primes.push_back(2);
for (int number = 3; number <= max; ++number)
{
bool flag = true;
for (int i = 0; i < primes.size(); ++i)
{
if (number%primes[i] == 0)
{
// if the current value is divisible by any of the values in
// the vector. If so, set the flag to false.
flag = false;
}
}
if (flag == true)
{
primes.push_back(number);
}
}
cout << \"Primes: \";
for (int i = 0; i < primes.size(); ++i)
{
cout << primes[i] << \" \";
}
cout << endl;
return 0;
}
/*
output:
Enter max: 200
Primes: 2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61
67 71 73 79 83 89 97 101 103 107 109 113 127 131
137 139 149 151 157 163 167 173 179 181 191 193 197 199
*/

