USACO 2.4.4 – Fractions to Decimals

#include <cstdio>
#include <vector>
#include <sstream>
using namespace std;
#define N 111111

int main() {
	freopen("fracdec.in", "r", stdin), freopen("fracdec.out", "w", stdout);
	int n, d, v[N] = { 0 };
	vector<int> f, h; stringstream ss;
	scanf("%d %d", &n, &d);
	if (n % d == 0) {
		printf("%d.0\n", n / d);
		return 0;
	}
	ss << n / d << '.';
	n %= d;
	while (n && !v[n]++) {
		h.push_back(n); n *= 10; f.push_back(n / d); n %= d;
	}
	for (size_t i = 0; i < f.size(); i++) {
		if (n && h[i] == n) ss << '(';
		ss << f[i];
		if (ss.str().size() % 76 == 0) {
			puts(ss.str().c_str()); ss.clear(); ss.str("");
		}
	}
	printf("%s", ss.str().c_str());
	puts((n ? ")" : ""));
	return 0;
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: