Skip to content

Instantly share code, notes, and snippets.

@XD-DENG
Last active November 27, 2015 07:51
Show Gist options
  • Save XD-DENG/308a361203f337d5024f to your computer and use it in GitHub Desktop.
Save XD-DENG/308a361203f337d5024f to your computer and use it in GitHub Desktop.
test
/*
// Skills included in this script:
// (1) FOR loop;
// (2) IF statement;
// (3) Get the current time;
// (4) Usage of vector (build, insert, size);
// (5) How to convert int into string;
// (6) Write into file;
// (7) Output;
*/
//---------------------------------------------------------------------------------------------
// Preprocessor part
// They are special lines interpreted before the compilation of the program itself begins.
#include <iostream> // header
#include <fstream> // use for file operation
#include <vector>
using namespace std;
int main() {
// recorde the time the code starts
time_t t1;
t1 = time(NULL);
int upper_limit = 100000;
vector<int> result;
for (int i = 0; i<=upper_limit; i++) {
vector<int> temp_result;
for (int j = 1; j<=i; j++) {
if (i%j == 0) {
temp_result.insert(temp_result.end(),j);
}
}
if (temp_result.size()==2) { // "1" and the prime number itself
result.insert(result.end(), i);
}
}
for (int k=0; k<result.size(); k++) {
cout<<result[k]<<"\n";
}
cout << "There are "<<result.size() << " prime number from 0 to "<<upper_limit<<"\n";
// write the results into a file
// http://www.cplusplus.com/doc/tutorial/files/
ofstream f;
string temp_file_name = to_string(upper_limit); // the easy way to convert an "int" into "string"
f.open("/Users/nus/prime numbers from 1 to "+temp_file_name+".csv");
for(int i=0; i<result.size() ; i++){
f << result[i] << "\n";
}
f.close();
// recorde the time the code ends, and compute the time elapsed
time_t t2;
t2 = time(NULL);
cout << t1 << endl;
cout << t2 << endl;
cout << t2-t1 << " seconds elapsed." << endl;
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment