Rational

1081 Rational Sum

Link

#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <algorithm>
#include <string>
#include <string.h>
#include <vector>
#include <cmath>
using namespace std;
typedef long long ll;
int n;
ll ca,cb;
ll a[110],b[110];
inline ll gcd(ll x,ll y){
	x=abs(x),y=abs(y);
	while(y^=x^=y^=x%=y);
	return x;
}
int main() {
	scanf("%d",&n);
	for(int i=1;i<=n;++i){
		scanf("%lld/%lld",&a[i],&b[i]);
		int g=gcd(a[i],b[i]);
		a[i]/=g,b[i]/=g;
	}
	ca=a[1],cb=b[1];
	for(int i=2;i<=n;++i){
		ll gb=gcd(cb,b[i]);
		ll tb=(cb/gb)*b[i];
		ll ta=ca*(tb/cb)+a[i]*(tb/b[i]);
		if(tb<0){
			tb=-tb;
			ta=-ta;
		}
		int g=gcd(ta,tb);
		ca=ta/g,cb=tb/g;
	}
	if(ca<0){
		printf("-");
		ca=-ca;
	}
	if(ca%cb==0) printf("%lld\n",ca/cb);
	else{
		if(ca/cb) printf("%lld ",ca/cb);
		printf("%lld/%lld\n",ca%cb,cb);
	}
	return 0;
}

1088 Rational Arithmetic

Link

#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <algorithm>
#include <string>
#include <string.h>
#include <vector>
using namespace std;
typedef long long ll;
string op[4]={"+","-","*","/"};
string s1,s2;
ll pos,n1,d1,n2,d2;
inline ll gcd(ll a,ll b) {
	while(b^=a^=b^=a%=b);
	return a;
}
void prllNumber(ll n,ll d){
	if(n==0) cout<<"0";
	else{
		ll f=1;
		if((n<0&&d>0)||(n>0&&d<0)){
			f=-1;
			n=abs(n),d=abs(d);
		}
		ll g=gcd(n,d);
		n/=g,d/=g;
		if(f<0) cout<<"(-";
		if(n%d==0) cout<<n/d;
		else{
			if(n>d) cout<<n/d<<" "<<n%d;
			else cout<<n;
			cout<<"/"<<d;
		}
		if(f<0) cout<<")";
	}
}
void prllLine(ll opIdx){
	prllNumber(n1,d1);
	cout<<" "<<op[opIdx]<<" ";
	prllNumber(n2,d2);
	cout<<" = ";
	ll n3,d3;
	if(op[opIdx]=="+"){
		n3=n1*d2+n2*d1,d3=d1*d2;
	}else if(op[opIdx]=="-"){
		n3=n1*d2-n2*d1,d3=d1*d2;
	}else if(op[opIdx]=="*"){
		n3=n1*n2,d3=d1*d2;
	}else{
		if(n2==0){cout<<"Inf"<<endl;return;}
		n3=n1*d2,d3=d1*n2;
	}
	prllNumber(n3,d3);
	cout<<endl;
}
int main() {
	cin>>s1>>s2;
	pos=s1.find("/");
	n1=stoi(s1.substr(0,pos));
	d1=stoi(s1.substr(pos+1));

	pos=s2.find("/");
	n2=stoi(s2.substr(0,pos));
	d2=stoi(s2.substr(pos+1));

	prllLine(0);
	prllLine(1);
	prllLine(2);
	prllLine(3);
	return 0;
}
posted @ 2022-07-07 21:55  Ryomk  阅读(32)  评论(0编辑  收藏  举报