{ }codelper
GCDnegative remainder64-bit integersP0094

Add fractions and simplify

n fractions are given one per line in the form p/q (the numerator p may be negative, the denominator q is positive; input fractions are not necessarily in lowest terms).
Print the sum of all of them as a fraction in lowest terms: the numerator and denominator have greatest common divisor 1, the denominator is positive, and a negative sign goes on the numerator (e.g.
-1/12).
If the sum is an integer (including 0), print only the integer, with no / or denominator. The first line gives n, then n lines each give one fraction with no spaces.

Input
1 ≤ n ≤ 10, -100 ≤ p ≤ 100, 1 ≤ q ≤ 30
Output
A reduced fraction a/b (b ≥ 2) or a single integer
Example 1 · stdin
3
1/2
1/3
1/6
stdout
1
Example 2 · stdin
2
-1/4
1/6
stdout
-1/12
main.py
Input (stdin)

When you run, these lines are fed to input()/stdin in order (the program doesn't stop to ask).

$ Ready

Open this on a computer to write and run code. On mobile you can read the problem and the solutions.

In other languagesShow solutions by language · 8 languages

To add p/q to the running sum num/den, bring both to the least common multiple L = den / gcd(den, q) * q: num = num * (L / den) + p * (L / q), den = L, and reduce by gcd(num, den) every time.
Just multiplying denominators grows them to 30¹⁰ ≈ 6×10¹⁴ with numerators larger still, which is no longer exact in JavaScript, TypeScript and Craykon numbers (exact up to 2^53).
Even with the LCM the denominator reaches lcm(1…30) ≈ 2.3×10¹², so C, C++, Java and C# need long/long long, not int.
The biggest trap is the remainder of negatives: in C, C++, Java, C#, JavaScript, TypeScript and Craykon, % takes the sign of the left operand (-3 % 6 is -3), so a hand-written Euclid can return a negative gcd, and dividing by it makes the denominator negative (1/-12).
So take absolute values first inside gcd.
Python's % takes the sign of the right operand, and math.gcd and C++17 std::gcd/std::lcm (<numeric>) always return a non-negative value, so there is no such worry.
Java, C#, C and JavaScript have no built-in integer gcd (Java only has BigInteger.gcd), so you write one.
Craykon defines a gcd(a, b) function and uses Mathf.Abs and Mathf.Quot (/ is real division).
The input p/q is split with Python split("/"), C scanf("%lld/%lld"), C++ cin >> p >> slash >> q, Craykon Split("/").
Finally, a sum that is an integer is written 3 or 0, not 3/1 or 0/1.

Pythonmain.py · 13 lines
from math import gcd n = int(input())num, den = 0, 1  # 지금까지의 합 num/den (늘 기약분수, den > 0)for _ in range(n):    p, q = map(int, input().split("/"))    lcm = den // gcd(den, q) * q  # 두 분모의 최소공배수로 통분    num = num * (lcm // den) + p * (lcm // q)    den = lcm    g = gcd(num, den)  # math.gcd는 음수를 받아도 0 이상을 돌려준다    num //= g    den //= gprint(num if den == 1 else f"{num}/{den}")
JavaScriptmain.js · 22 lines
const lines = require("fs").readFileSync(0, "utf8").trim().split(/\r?\n/); // %는 앞 수의 부호를 따라서 음수가 들어오면 음수 gcd가 나올 수 있다 → 절댓값으로 계산const gcd = (a, b) => {  a = Math.abs(a);  b = Math.abs(b);  while (b !== 0) [a, b] = [b, a % b];  return a;}; const n = Number(lines[0]);let num = 0, den = 1; // 지금까지의 합 num/den (늘 기약분수, den > 0)for (let i = 1; i <= n; i++) {  const [p, q] = lines[i].trim().split("/").map(Number);  const lcm = (den / gcd(den, q)) * q; // 두 분모의 최소공배수로 통분  num = num * (lcm / den) + p * (lcm / q);  den = lcm;  const g = gcd(num, den);  num /= g;  den /= g;}console.log(den === 1 ? `${num}` : `${num}/${den}`);
TypeScriptmain.ts · 23 lines
import { readFileSync } from "node:fs";const lines: string[] = readFileSync(0, "utf8").trim().split(/\r?\n/); // %는 앞 수의 부호를 따라서 음수가 들어오면 음수 gcd가 나올 수 있다 → 절댓값으로 계산function gcd(a: number, b: number): number {  a = Math.abs(a);  b = Math.abs(b);  while (b !== 0) [a, b] = [b, a % b];  return a;} const n = Number(lines[0]);let num = 0, den = 1; // 지금까지의 합 num/den (늘 기약분수, den > 0)for (let i = 1; i <= n; i++) {  const [p, q] = lines[i].trim().split("/").map(Number);  const lcm = (den / gcd(den, q)) * q; // 두 분모의 최소공배수로 통분  num = num * (lcm / den) + p * (lcm / q);  den = lcm;  const g = gcd(num, den);  num /= g;  den /= g;}console.log(den === 1 ? `${num}` : `${num}/${den}`);
JavaMain.java · 32 lines
import java.util.Scanner; public class Main {    // %는 앞 수의 부호를 따라서 음수가 들어오면 음수 gcd가 나올 수 있다 → 절댓값으로 계산    static long gcd(long a, long b) {        a = Math.abs(a);        b = Math.abs(b);        while (b != 0) {            long t = a % b;            a = b;            b = t;        }        return a;    }     public static void main(String[] args) {        Scanner sc = new Scanner(System.in);        int n = Integer.parseInt(sc.nextLine().trim());        long num = 0, den = 1; // 지금까지의 합 num/den (늘 기약분수, den > 0)        for (int i = 0; i < n; i++) {            String[] pq = sc.nextLine().trim().split("/");            long p = Long.parseLong(pq[0]), q = Long.parseLong(pq[1]);            long lcm = den / gcd(den, q) * q; // 두 분모의 최소공배수로 통분            num = num * (lcm / den) + p * (lcm / q);            den = lcm;            long g = gcd(num, den);            num /= g;            den /= g;        }        System.out.println(den == 1 ? String.valueOf(num) : num + "/" + den);    }}
C#Main.cs · 31 lines
using System; class Program{    // %는 앞 수의 부호를 따라서 음수가 들어오면 음수 gcd가 나올 수 있다 → 절댓값으로 계산    static long Gcd(long a, long b)    {        a = Math.Abs(a);        b = Math.Abs(b);        while (b != 0) (a, b) = (b, a % b);        return a;    }     static void Main()    {        int n = int.Parse(Console.ReadLine());        long num = 0, den = 1; // 지금까지의 합 num/den (늘 기약분수, den > 0)        for (int i = 0; i < n; i++)        {            string[] pq = Console.ReadLine().Trim().Split('/');            long p = long.Parse(pq[0]), q = long.Parse(pq[1]);            long lcm = den / Gcd(den, q) * q; // 두 분모의 최소공배수로 통분            num = num * (lcm / den) + p * (lcm / q);            den = lcm;            long g = Gcd(num, den);            num /= g;            den /= g;        }        Console.WriteLine(den == 1 ? $"{num}" : $"{num}/{den}");    }}
C++main.cpp · 21 lines
#include <iostream>#include <numeric> int main() {    int n;    std::cin >> n;    long long num = 0, den = 1; // 지금까지의 합 num/den (늘 기약분수, den > 0)    for (int i = 0; i < n; i++) {        long long p, q;        char slash;        std::cin >> p >> slash >> q;        long long lcm = std::lcm(den, q); // 두 분모의 최소공배수로 통분        num = num * (lcm / den) + p * (lcm / q);        den = lcm;        long long g = std::gcd(num, den); // std::gcd는 음수를 받아도 0 이상을 돌려준다        num /= g;        den /= g;    }    if (den == 1) std::cout << num << '\n';    else std::cout << num << '/' << den << '\n';}
Cmain.c · 33 lines
#include <stdio.h>#include <stdlib.h> /* %는 앞 수의 부호를 따라서 음수가 들어오면 음수 gcd가 나올 수 있다 → 절댓값으로 계산 */static long long gcd(long long a, long long b) {    a = llabs(a);    b = llabs(b);    while (b != 0) {        long long t = a % b;        a = b;        b = t;    }    return a;} int main(void) {    int n;    scanf("%d", &n);    long long num = 0, den = 1; /* 지금까지의 합 num/den (늘 기약분수, den > 0) */    for (int i = 0; i < n; i++) {        long long p, q;        scanf("%lld/%lld", &p, &q);        long long lcm = den / gcd(den, q) * q; /* 두 분모의 최소공배수로 통분 */        num = num * (lcm / den) + p * (lcm / q);        den = lcm;        long long g = gcd(num, den);        num /= g;        den /= g;    }    if (den == 1) printf("%lld\n", num);    else printf("%lld/%lld\n", num, den);    return 0;}
Craykonmain.cray · 37 lines
// %는 앞 수의 부호를 따라서 음수가 들어오면 음수 gcd가 나올 수 있다 → 절댓값으로 계산최대공약수(a, b){    a = Mathf.Abs(a);    b = Mathf.Abs(b);    while (b != 0)    {        t = a % b;        a = b;        b = t;    }    return a;} n = Console.ReadLine().ToNumber();num = 0;den = 1; // 지금까지의 합 num/den (늘 기약분수, den > 0)for (i = 0; i < n; i++){    pq = Console.ReadLine().Trim().Split("/");    p = pq[0].ToNumber();    q = pq[1].ToNumber();    lcm = Mathf.Quot(den, 최대공약수(den, q)) * q; // 두 분모의 최소공배수로 통분    num = num * Mathf.Quot(lcm, den) + p * Mathf.Quot(lcm, q);    den = lcm;    g = 최대공약수(num, den);    num = Mathf.Quot(num, g);    den = Mathf.Quot(den, g);}if (den == 1){    Console.WriteLine(num);}else{    Console.WriteLine(num + "/" + den);}