A rational is a number that can be expressed as
B are integers,
B is positive, and
B are co-prime.
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
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
f(r) must be defined for all rationals
g(n) for all integers
f(a) == f(b) if and only if
a == b;
g(p) == g(q) if and only if
p == q.
- You can take the rational and the integer in any sensible format.
- You can choose different format for
g, but the format must be consistent within
- 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.
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
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.