Return to Snippet

Revision: 42223
at March 2, 2011 02:37 by tom76kimo


Updated Code
#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;
}

Revision: 42222
at March 1, 2011 20:18 by tom76kimo


Initial Code
#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);

	for(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;
}

Initial URL


Initial Description


Initial Title
《The 3n + 1 problem》

Initial Tags


Initial Language
C++