Definition
A rational is a number that can be expressed as A/B
where A
and B
are integers, B
is positive, and A
and B
are co-prime.
Task
You are to write two programs/functions, one which takes a rational and output an integer, another which takes an integer and outputs a rational.
Denote the two functions as f
and g
respectively.
They are meant to be inverses of each other, meaning that f(g(n)) = n
and g(f(r)) = r
for all integers n
and all rationals r
.
f(r)
must be defined for all rationals r
and g(n)
for all integers n
.
f(a) == f(b)
if and only if a == b
; g(p) == g(q)
if and only if p == q
.
Specs
- You can take the rational and the integer in any sensible format.
- You can choose different format for
f
andg
, but the format must be consistent withinf
and withing
. - You can assume that the rational input is simplified.
- You do not need to simplify the rational output.
- The two functions/programs must be stand-alone.
Testcases
Below are valid rational inputs:
0/1
1/1
5/7
-1/3
Below are invalid rational inputs:
2/4 (can be output)
0/0
3/0
3/-4
-1/-5
Note
1/2
and 2/4
must map to the same integer, although only the former will be supplied.
As always, if my problem is not clear enough, please address in the comments.