# Untitled

unknown
c_cpp
2 years ago
3.3 kB
6
Indexable
Never
#include <iostream>
#include <vector>
#include <iomanip>
#include <string>
#include <cmath>
#include <algorithm>
#include <limits>

using namespace std;

// declaration of functions
void sieve(int x);
void print(vector<string> str);
int user_input();

string lines = "\n----------------------------------------------------------------------------------------------------\n";

int main(){
cout << lines << setw(73) <<"Welcome to the Sieve of Eratosthenes Program!" << lines << endl;
// call the sieve function and ask for user input
sieve(user_input());
cout << lines << "Submitted by: Paras, Raymundo, Rosal, and Roxas. :>\n";
return 0;
}

void sieve(int x){
// declare vectors to store respected data
vector<int> table;
vector<string> marked_table;
vector<int> prime;
vector<int> composite;

// store x values inside the vectors
for(int i = 1; i <= x; i++){
table.push_back(i);
//marked_table.push_back(to_string(i));
}
for(int m = 1; m <= x; m++){
marked_table.push_back("[" + to_string(m) + "]");
}

// marking index(0) since 1 is always composite
replace(marked_table.begin(), marked_table.end(), marked_table.at(0), to_string(1));

for(int j = 2; j <=  sqrt(x) ; j++){               //loop until j is equals to sqrt(x) times
for(int k = j; (k * j) <= x; k++){              //iterate until k*j < x
if( (k * j) % (table.at(j-1)) == 0){  //if remainder none
for(int l = 2 ; l <= x; l++){        // loop till it reaches x
if(table.at(l-1) == k*j) {// if table element == k*j
// then MARK that table element.
replace(marked_table.begin(), marked_table.end(), marked_table.at(l - 1), to_string(k * j));
}
else
continue;
}
}
}
}
}
// call the print function to print table to terminal
print(marked_table);

std::sort(composite.begin(), composite.end());
composite.erase(unique(composite.begin(),composite.end()), composite.end());
for(auto printcomp : composite){
cout << printcomp << " ";
}
cout << endl << endl;

}

void print(vector<string> str){
int counter = 0;    //declared a counter for table formatting
for(auto print : str){  // for each loop to print all elements of the vector
cout << setfill(' ') << setw(10) << print;  // used IOMANIP library functions to format the table uniformly

counter++; // iterate counter by 1
if(counter == 10){  // if counter is equal to 10
// then linebreak
cout << endl;
counter = 0;    // reset counter to 0
}
}
}

// function that takes user input
int user_input(){
//variable to put user's input
int x;
cout << "Enter a number: ";
cin >> x; // store user input
cout << endl;

if (cin.fail()) {
cin.clear(); // Clear the error flag
cin.ignore(numeric_limits<streamsize>::max(), '\n'); // Discard the input
cout << "That's not a number. Please input a valid positive number!" << endl;
}
else {
return x;
}
}