PAT乙级1034

题目链接
坑点

1、求最大公约数的复杂度要低,不然后两个测试点会超时
2、数据类型全部用long long(真的瓜皮)

实现


#include <cstdio>
#include <iostream>
#include <string>
typedef long long ll;
using namespace std;
long long getMaxCommNum(long long a, long long b)
/*得到最大公约数*/
{
	long long m = a % b;  
    while(m) {  
        a = b;  
        b = m;  
        m = a % b;  
    }  
    return b; 
}
string getSimpExp(long long a, long long b)
{
	string exp = "";
	if (a == 0)
		return "0";
	if (a < 0)
		exp += "(-";
	if (abs(a) >= b)	//这里是绝对值进行比较
	{
		long long k = abs(a) / b;
		exp += to_string(k);
		
		long long temp = abs(a) - k*b;	
		if (temp)
		{
			exp += " ";
			long long common = getMaxCommNum(temp, b);
			temp = temp / common;
			b = b / common;
			exp += to_string(temp);
			exp += "/";
			exp += to_string(b);
		}
	}
	if (abs(a) < b)
	{
		long long common = getMaxCommNum(abs(a), b);
		a = a / common;
		b = b / common;
		exp += to_string(abs(a));
		exp += "/";
		exp += to_string(b);
	}
	if (a < 0)
		exp += ")";
	return exp;
}
int main()
{
	
	long long a1, b1, a2, b2,tempA,tempB;
	scanf("%lld/%lld %lld/%lld", &a1, &b1,&a2,&b2);
	string str1 = getSimpExp(a1, b1);
	string str2 = getSimpExp(a2, b2);
	int i;
	string resStr;
	tempB = b1*b2;
	for (i = 0; i < 4; i++)
	{
		switch (i)
		{
		case 0:printf("%s + %s = ", str1.c_str(), str2.c_str());
			tempA = a1*b2 + a2*b1;
			resStr = getSimpExp(tempA, tempB); break;
		case 1:printf("%s - %s = ", str1.c_str(), str2.c_str());
			tempA = a1*b2 - a2*b1;
			resStr = getSimpExp(tempA, tempB); break;
		case 2:printf("%s * %s = ", str1.c_str(), str2.c_str());
			tempA = a1*a2;
			resStr = getSimpExp(tempA, tempB); break;
		case 3:printf("%s / %s = ", str1.c_str(), str2.c_str());
			if (a2 == 0)
				resStr = "Inf";
			else
			{
				tempA = abs(a1*b2);
				tempB = abs(b1*a2);
				if (a1*a2 < 0)
					tempA = 0 - tempA;
				resStr = getSimpExp(tempA, tempB);
			}
			break;
		
		}
		printf("%s\n", resStr.c_str());
	}
	return 0;
}



  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值