/ Published in: C++
Expand |
Embed | Plain Text
Copy this code and paste it in your HTML
#include <cstdlib> #include <iostream> #include <fstream> #include <ctime> using namespace std; int three_n_plus_one(unsigned int n) { int times(1); //cout << n << " "; if(n == 1) return times; if((n%2) == 1) times += three_n_plus_one( ((n*3)+1) ); else times += three_n_plus_one( (n/2) ); return times; } int find_max_times(unsigned int begin, unsigned int end) { int max(0); int temp_result(0); int temp_begin_end(0); if(begin > end) { temp_begin_end = end; end = begin; begin = temp_begin_end; } for(unsigned int i=begin; i<=end; ++i) { temp_result = three_n_plus_one(i); if(temp_result > max) max = temp_result; } return max; } int main(int argv, char* argc[]) { clock_t start = clock(); string out_file_name(argc[1]); out_file_name.replace(5, 2, "out"); ifstream fin(argc[1], ios::in); ofstream fout(out_file_name, ios::out); unsigned int begin(0), end(0); while(!fin.eof()) { fin >> begin; fin >> end; if(!begin || !end) { cout << "read invalid value" << endl; exit(1); } fout << begin << " " << end << " " << find_max_times(begin, end) << " "; } fin.close(); fout.close(); cout << "cost :" << clock()-start << "ms" << endl; return 0; }