NC25859. 分数的运算
描述
输入描述
一行
输出描述
四行,每行两个整数x,y代表答案为,第一行输出和,第二行输出差,第三行输出积,第四行输出商答案为最简分数形式。
如果答案为0则输出0 0
示例1
输入:
1 2 1 2
输出:
1 1 0 0 1 4 1 1
说明:
Java 解法, 执行用时: 43ms, 内存消耗: 10720K, 提交时间: 2023-08-08 11:32:34
import java.util.Scanner; public class Main { public static void main(String []args) { Scanner sc=new Scanner(System.in); long a=sc.nextInt(); long b=sc.nextInt(); long c=sc.nextInt(); long d=sc.nextInt(); long t=b*d/gcd(b,d); long x=a*t/b; long y=c*t/d; long s=x+y; System.out.println(s/gcd(s,t)+" "+t/gcd(s,t)); if(x-y==0) System.out.println(0+" "+0); else { if(x-y>0) { s=x-y; System.out.println(s/gcd(s,t)+" "+t/gcd(s,t)); } else { s=y-x; System.out.println(-s/gcd(s,t)+" "+t/gcd(s,t)); } } System.out.println(a*c/gcd(a*c,b*d)+" "+b*d/gcd(a*c,b*d)); System.out.println(a*d/gcd(a*d,b*c)+" "+b*c/gcd(a*d,b*c)); } public static long gcd(long a,long b) { return (b==0)?a:gcd(b,a%b); } }
Python3 解法, 执行用时: 43ms, 内存消耗: 4592K, 提交时间: 2023-08-08 11:31:09
x1, y1, x2, y2 = map(int, input().strip().split()) def gcd(x, y): a, b = x, y while a and b: a, b = abs(a-b), a return x//(a+b), y//(a+b) for x ,y in [[x1*y2+x2*y1, y1*y2], [x1*y2-x2*y1, y1*y2], [x1*x2, y1*y2], [x1*y2, x2*y1]]: if x == 0: print(0, 0) elif x*y < 0: r1, r2 = gcd(abs(x), abs(y)) print(-1*r1, r2) else: r1, r2 = gcd(abs(x), abs(y)) print(r1, r2)
C++ 解法, 执行用时: 3ms, 内存消耗: 416K, 提交时间: 2023-08-08 11:54:14
#include <bits/stdc++.h> using namespace std; void f(int x,int y) { int t; t=__gcd(x,y); printf("%d %d\n",x/t,y/t); } int main() { int x1,y1,x2,y2; cin>>x1>>y1>>x2>>y2; f(x1*y2+x2*y1,y1*y2); if(x1*y2-x2*y1==0) cout<<"0 0"<<endl; else f(x1*y2-x2*y1,y1*y2); f(x1*x2,y1*y2); f(x1*y2,x2*y1); }