All pastes #626265 Raw Edit

God

public text v1 · immutable
·published 2007-07-19 15:08 UTC
rendered paste body
/*
ID: richard20
PROG: fracdec
LANG: C++
*/

using namespace std;

#include<iostream>
#include<fstream>
#define MAXSIZE 1000000

typedef pair<int,int> PINT;

PINT store [MAXSIZE];

ostream& operator<< (ostream& out, PINT& p)
{
	out << p.first << " r " << p.second;
	return out;
}

void print ()
{
	cout << "PRINT" << endl;
	for (int i = 0 ; i < MAXSIZE ; i ++)
	{
		if (store[i].first == 0 && store[i].second == 0) break;
		cout << store[i] << endl;
	}
}

PINT divide(int n, int d)
{
	//cout << "DIV -> " << n << " / " << d << endl;
	return PINT(n/d,n%d);
}

int log(int i)
{
	if (i < 10) return 1;
	if (i < 100) return 2;
	if (i < 1000) return 3;
	if (i < 10000) return 4;
	if (i < 100000) return 5;
	if (i < 1000000) return 6;
	if (i < 10000000) return 7;
	
	return 8;
}

int main ()
{
	
	ifstream in ("fracdec.in");
	
	int n,d;
	
	in >> n >> d;
	
	//cout << n << " / " << d << endl;
	
	//cout << n/d << endl;
	
	//n -= (n/d)*d;
	//cout << n << " / " << d << endl;
	
	store[0] = divide(n,d);
	int startb = -1;
	int endb = -1;
	
	// the O(N^2 algo)
	int i;
	for (i = 1 ; i < MAXSIZE ; i ++)
	{
		store[i] = divide(store[i-1].second*10,d);
		//check
		if (store[i].second == 0)
		{
			i++;
			break;
		}
		
		for (int j = 1 ; j < i ; j ++)
		{
			if (store[i] == store[j])
			{
				startb = j;
				goto end;
			}
		}
		
		//cout << div << endl;
	}
end:
	
	//cout << startb << endl;

	//print();
	
	int decplace = log(n/d);
	int caret = 0;
	char str [MAXSIZE];
	
	for (int j = 1 ; j < i ; j++)
	{
		if (j == startb)
		{
			
			str[caret++] = '(';
			startb = -2;
			j--;
			continue;
		}
		str[caret++] = '0'+(store[j].first);
		//cout << store[j].first;
	}
	if (startb != -1)
		str[caret++] = ')';
	
	
	
	ofstream out("fracdec.out");
	
	
	int pushover = 76;
	cout << (n/d) << '.';
	int count = log(n/d);
	for (int i = 0 ; i < caret ; i++)
	{
		count++;
		if (count == pushover)
		{
			count = 0;
			cout << '\n';
		}
		cout << str[i];
	}
	cout << endl;
	
	out.close();
	return 0;
}