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 isprime 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.
// 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 isprime 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.
#include <iostream>
#include <vector>
int main()
{
// "...Start with a vector called primes..."
std::vector<int> primes;
// "...and push back 2 as it is prime..."
primes.push_back(2);
// "...all the prime numbers between 2 and max..."
std::cout << "\nPlease, specify the upper bound: ";
int max;
std::cin >> max;
// "...Then use a for loop from 3 to max..."
for(int curr_value=3; curr_value<max; curr_value++) {
// "...1. Set a flag isprime to true at the beginning
/// of each iteration..."
bool isprime = true;
// "...2. Use a for loop over the primes..."
for(int i=0; i<primes.size(); i++) {
// "...to see if the current value is divisible by any
// of the values in the vector..."
if(curr_value % primes.at(i) == 0) {
// "...If so, set the flag to false..."
isprime = false;
}
}
// "...3. Depending on the flag, push back the current value
// into the vector of primes..."
if(isprime) { // <-- if(isprime == true)
primes.push_back(curr_value);
}
}
for(int i=0; i<primes.size(); i++) {
std::cout << primes.at(i) << ' ';
}
std::cout << '\n';
return 0;
}