您的位置:首页 > 其它

PAT 1081. Rational Sum (20)

2016-01-31 19:45 489 查看
http://www.nowcoder.com/pat/1/problem/4311

挺简单的题目,但是卡了好久,主要太久没做手生了。

牢记最小公倍数的函数

注意负数情况的处理

最后的输出是有要求的

#include<stdio.h>
#include<iostream>
#include<math.h>

using namespace std;

long long a[101],b[101];

long long gcd(long long x,long long y)
{
return y?gcd(y,x%y):x;
}

int main(){

long long n,suma,sumb,sumc;

long long i,j,k;
scanf("%lld",&n);
for(i=0;i<n;i++)
scanf("%lld/%lld",&a[i],&b[i]);

long long temp1,temp2,temp;
temp1=a[0];temp2=b[0];
for(i=1;i<n;i++)
{
temp1=temp1*b[i]+temp2*a[i];
temp2=temp2*b[i];
//           temp=gcd(temp1,temp2);
//           temp1/=temp;
//           temp2/=temp;

}

//        printf("\n");
//        printf("%lld\n",temp);
//        printf("%lld %lld\n",temp1,temp2);
//        printf("\n");

if(temp1>=0)
{
temp=gcd(temp1,temp2);
temp1/=temp;
temp2/=temp;
suma=temp1/temp2;
sumb=temp1-suma*temp2;
sumc=temp2;
if(suma==0&&sumb!=0)
printf("%lld/%lld",sumb,sumc);

else if(sumb==0)
printf("%lld",suma);
else
printf("%lld %lld/%lld",suma,sumb,sumc);
}

else
{
temp1=-temp1;
temp=gcd(temp1,temp2);
temp1/=temp;
temp2/=temp;
suma=temp1/temp2;
sumb=temp1-suma*temp2;
sumc=temp2;

if(suma==0)
sumb=-sumb;
else
suma=-suma;

if(suma==0&&sumb!=0)
printf("%lld/%lld",sumb,sumc);

else if(sumb==0)
printf("%lld",suma);
else
printf("%lld %lld/%lld",suma,sumb,sumc);
}

return 0;
}

//2
//-1/3 2/3
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: