our task is to find the sum of two fractions, expr...

Created on: June 23, 2025

Answered using O3 by Chat01

Question

our task is to find the sum of two fractions, expressed in the form
X
/
Y
X/Y and
U
/
V
U/V, where
X
X,
Y
Y,
U
U, and
V
V are four integers. Compute their sum and reduce it to its lowest indivisible state:
A
/
B
A/B.

For example:

2
/
6
+
2
/
6
2/6+2/6 equals
4
/
6
4/6, which should be reduced to
2
/
3
2/3.
7
/
10
+
13
/
10
7/10+13/10 equals
20
/
10
20/10 which should be reduced to
2
/
1
2/1.
You are given an array of strings, which contains several expressions in the form "X/Y+U/V". Return a string array, where the
i
i-th element is the result for the
i
i-th expression in the form "A/B".

Example

For fractions = ["2/6+2/6", "7/10+13/10"], the output should be solution(fractions) = ["2/3", "2/1"]

in c++ without comments

Thought

Providing C++ code

Got it! The user wants a C++ code snippet that takes in a vector of strings, each representing a fraction, and returns a vector of strings with the fractional sum. I'll focus just on the code without any comments.

The approach seems to involve parsing the input strings, performing the necessary arithmetic, simplifying using GCD, and returning the results. I'll include everything in a minimal code snippet below. Let's stick to the original request — clear, simple, and no frills.

Thought for 15 seconds

Answer

cpp
#include <bits/stdc++.h> using namespace std; vector<string> solution(const vector<string>& fractions) { vector<string> res; for (const string& expr : fractions) { size_t a = expr.find('/'); size_t b = expr.find('+', a); size_t c = expr.find('/', b); long long X = stoll(expr.substr(0, a)); long long Y = stoll(expr.substr(a + 1, b - a - 1)); long long U = stoll(expr.substr(b + 1, c - b - 1)); long long V = stoll(expr.substr(c + 1)); long long num = X * V + U * Y; long long den = Y * V; long long g = std::gcd(num, den); res.push_back(to_string(num / g) + "/" + to_string(den / g)); } return res; }

Share this Q&A