题目链接
坑点
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;
}