A rational number is defined as the quotient of two integers a
and b
, called the numerator and denominator, respectively, where b != 0
.
The absolute value |r|
of the rational number r = a/b
is equal to |a|/|b|
.
The sum of two rational numbers rβ = aβ/bβ
and rβ = aβ/bβ
is rβ + rβ = aβ/bβ + aβ/bβ = (aβ * bβ + aβ * bβ) / (bβ * bβ)
.
The difference of two rational numbers rβ = aβ/bβ
and rβ = aβ/bβ
is rβ - rβ = aβ/bβ - aβ/bβ = (aβ * bβ - aβ * bβ) / (bβ * bβ)
.
The product (multiplication) of two rational numbers rβ = aβ/bβ
and rβ = aβ/bβ
is rβ * rβ = (aβ * aβ) / (bβ * bβ)
.
Dividing a rational number rβ = aβ/bβ
by another rβ = aβ/bβ
is rβ / rβ = (aβ * bβ) / (aβ * bβ)
if aβ
is not zero.
Exponentiation of a rational number r = a/b
to a non-negative integer power n
is r^n = (a^n)/(b^n)
.
Exponentiation of a rational number r = a/b
to a negative integer power n
is r^n = (b^m)/(a^m)
, where m = |n|
.
Exponentiation of a rational number r = a/b
to a real (floating-point) number x
is the quotient (a^x)/(b^x)
, which is a real number.
Exponentiation of a real number x
to a rational number r = a/b
is x^(a/b) = root(x^a, b)
, where root(p, q)
is the q
th root of p
.
Implement the following operations:
Your implementation of rational numbers should always be reduced to lowest terms. For example, 4/4
should reduce to 1/1
, 30/60
should reduce to 1/2
, 12/8
should reduce to 3/2
, etc. To reduce a rational number r = a/b
, divide a
and b
by the greatest common divisor (gcd) of a
and b
. So, for example, gcd(12, 8) = 4
, so r = 12/8
can be reduced to (12/4)/(8/4) = 3/2
.
Assume that the programming language you are using does not have an implementation of rational numbers.
Sign up to Exercism to learn and master Delphi Pascal with 76 exercises, and real human mentoring, all for free.