Untitled
unknown
c_cpp
2 years ago
2.3 kB
9
Indexable
#include <iostream> #include <vector> #include <iomanip> #include <string> #include <cmath> #include <algorithm> using namespace std; void sieve(int x); void print(vector<string> str); int user_input(); int main(){ // call the sieve function and ask for user input sieve(user_input()); return 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; return x; // return user inpit } void sieve(int x){ // declare vectors to store respected data vector<int> table; vector<string> marked_table; // store x values inside the vectors for(int i = 1; i <= x; i++){ table.push_back(i); marked_table.push_back(to_string(i)); } // 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 if(table.at(j-1)){ //if reading element 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) + "]"); } } } } } } // call the print function to print table to terminal print(marked_table); } 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 } } }
Editor is loading...