中級 0件解決済み 正答率0%

Exact Fraction Arithmetic

Perform fraction operations and return a reduced fraction.

Represent a fraction as [numerator, denominator]. Apply operation to first and second: add, subtract, multiply, or divide. For absolute, use only first. For power, raise first to the integer exponent and ignore second. Return lowest terms with a positive denominator. Normalize zero to [0, 1]. All divisions and negative powers in valid inputs are defined.

Implement rational_arithmetic(operation, first, second, exponent).

Input

operation: The operation name.

first: Two integers representing the first fraction.

second: Two integers representing the second fraction; use [0, 1] when unused.

exponent: The exponent for power; use 0 for other operations.

Output

Return [numerator, denominator] in reduced form with a positive denominator.

制約

operation is add, subtract, multiply, divide, absolute, or power. Both fraction components have magnitude at most 100; denominators are nonzero. −6 ≤ exponent ≤ 6. For divide, second has nonzero numerator. For a negative power, first has nonzero numerator. The 0th power is [1, 1], including 0⁰ by this task’s convention. Values fit signed 64-bit.

例

例 1
入力:
first = [1, 6]
second = [1, 4]
exponent = 0
operation = "add"

期待される出力:
expected = [5, 12]
入力:
std::vector<long long> first = {1, 6};
std::vector<long long> second = {1, 4};
long long exponent = 0;
std::string operation = "add";

期待される出力:
std::vector<long long> expected = {5, 12};
入力:
long[] first = new long[] {1, 6};
long[] second = new long[] {1, 4};
long exponent = 0;
string operation = "add";

期待される出力:
long[] expected = new long[] {5, 12};

解説

1/6 + 1/4 = 2/12 + 3/12 = 5/12, already reduced.

例 2
入力:
first = [2, 3]
second = [0, 1]
exponent = -2
operation = "power"

期待される出力:
expected = [9, 4]
入力:
std::vector<long long> first = {2, 3};
std::vector<long long> second = {0, 1};
long long exponent = -2;
std::string operation = "power";

期待される出力:
std::vector<long long> expected = {9, 4};
入力:
long[] first = new long[] {2, 3};
long[] second = new long[] {0, 1};
long exponent = -2;
string operation = "power";

期待される出力:
long[] expected = new long[] {9, 4};

解説

A negative exponent inverts the fraction: (2/3)⁻² = (3/2)² = 9/4.

参考資料

この課題はCodeUtility用に調整されています。上記の説明と制約に従ってください。

他の人の解答から学ぶ

コミュニティの解答

まだ公開された解答がありません。この課題を解いて最初の解答を共有しましょう。