1088. Rational Arithmetic (20)

#include <iostream>

using namespace std;

long long getsame(long long a, long long b)
{
	if(b != 0)
	{
		return getsame(b, a % b);
	}
	else
	{
		return a;
	}
}

void simplify(long long &a, long long &b)
{
	if(a == 0)
	{
		b = 1;
		return;
	}

	if(b == 0) 
	{
		a = 1;
		return;
	}

	int aflag = 1, bflag = 1;
	if(a < 0)
	{
		a = -a;
		aflag = -1;
	}
	if(b < 0)
	{
		b = -b;
		bflag = -1;
	}

	long long same = getsame(a, b);
	a /= same;
	b /= same;

	a *= aflag * bflag;
}

void print(long long a, long long b)
{
	if(b == 0)
	{
		printf("Inf");
		return;
	}

	if(a == 0)
	{
		printf("0");
		return;
	}

	int flag = 0;
	if(a < 0)
	{
		printf("(");
		flag = 1;
	}

	long long x = a / b;
	if(x != 0)
	{
		printf("%lld", x);

		if(a % b == 0)
		{
			if(flag == 1)
			{
				printf(")");
			}

			return;
		}

		if(flag == 1)
		{
			a = -a;
		}

		if(x < 0)
		{
			x = -x;
		}

		printf(" ");
	}

	a -= x * b;
	printf("%lld/%lld", a, b);

	if(flag == 1)
	{
		printf(")");
	}
}

int main()
{
	long long a, b, c, d;
	scanf("%lld/%lld %lld/%lld", &a, &b, &c, &d);

	simplify(a, b);
	simplify(c, d);

	print(a, b);
	printf(" + ");
	print(c, d);
	printf(" = ");

	long long e = a * d + b * c, f = b * d;
	simplify(e, f);
	print(e, f);

	printf("\n");

	print(a, b);
	printf(" - ");
	print(c, d);
	printf(" = ");

	e = a * d - b * c;
	f = b * d;
	simplify(e, f);
	print(e, f);

	printf("\n");

	print(a, b);
	printf(" * ");
	print(c, d);
	printf(" = ");

	e = a * c;
	f = b * d;
	simplify(e, f);
	print(e, f);

	printf("\n");

	print(a, b);
	printf(" / ");
	print(c, d);
	printf(" = ");

	e = a * d;
	f = b * c;
	simplify(e, f);
	print(e, f);

	printf("\n");

	system("pause");
	return 0;
}

 

posted on 2025-11-23 17:20  王景迁  阅读(0)  评论(0)    收藏  举报

导航