您的位置:首页 > 其它

PAT L1-009. N个数求和(辗转相除法,浮点和输出注意)

2016-12-07 09:57 459 查看

题目地址

https://www.patest.cn/contests/gplt/L1-009

ac代码

#include <cstdio>
#include <cstdlib>
#include <cmath>
#include <cstring>
#include <iostream>
#include <string>
#include <vector>
#include <queue>
#include <algorithm>
#include <sstream>
#include <stack>
#include <map>
#include <set>
#include <unordered_map>

using namespace std;

const int INF = 0x7fffffff;
const int MIN_INF = - INF -1;
typedef long long int LL;

// 最大公约数
LL gcs(LL n , LL m)
{
if(n < m)
{
LL tmp = n;
n = m;
m = tmp;
}
// n >= m
LL r = n % m;
while(r != 0)
{
n = m;
m = r;
r = n % m;
}
return m;
}

int n;

int main()
{
//freopen("in.txt","r",stdin);
while(scanf("%d", &n) != EOF)
{
LL a1 = 0, b1 = 1;
LL a2, b2;
for(int i=0;i<n;i++)
{
scanf("%lld/%lld",&a2,&b2);
if(a2 == 0)
{
continue;
}
LL yue = gcs(b1,b2);
LL gong = b1 * b2 / yue;

LL tmp1 = a1 * gong / b1;
LL tmp2 = a2 * gong / b2;

LL tmp = tmp1 + tmp2 ;
if(tmp == 0)
{
a1 = 0;
b1 = 1;
continue;
}
LL flag = 1;
if(tmp < 0){
flag = -1;
tmp = -tmp;
}
LL yue2 = gcs(tmp, gong);

a1 = flag * tmp / yue2;
b1 = gong / yue2;
}

if(a1 == 0){
printf("0\n");
}else{
if(a1 < 0)
{
printf("-");
a1 = -a1;
}
if(b1 == 1)
{
printf("%lld\n",a1);
}else{
if(a1 % b1 == 0)
{
printf("%lld\n", a1 / b1);
}else{
LL t = a1 / b1;
LL t2 = a1 % b1;
if(t != 0)
{
printf("%lld ",t);
printf("%lld/%lld\n", a1 - t * b1, b1);
}else{
printf("%lld/%lld\n", a1 - t * b1, b1);
}
}
}

}
}// end while
//printf("\n");
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: