I recently learned from a comment by MathOverflow user pregunton that it is possible to enumerate all rational numbers using iterated maps of the form \$f(x) = x+1\$ or \$\displaystyle g(x) = -\frac 1x\$, starting from \$0\$.
For example, $$0 \overset{f}{\mapsto} 1 \overset{f}{\mapsto} 2 \overset{g}{\mapsto} -\frac12 \overset{f}{\mapsto} \frac12 \overset{f}{\mapsto} \frac 32 \overset{g}{\mapsto} -\frac23 \overset{f}{\mapsto} \frac 13.$$
That is, $$ \frac13 = f(g(f(f(g(f(f(0))))))) = f\circ g\circ f\circ f\circ g\circ f\circ f(0).$$ This is an example of a shortest path of iterated maps to reach \$\frac13\$; every path from \$0\$ to \$\frac13\$ requires at least seven steps.
Challenge
Your challenge is to take two integers, n
and d
, and return a string of f
's and g
's that represents a shortest path of iterated maps from \$0\$ to \$\displaystyle\frac nd\$.
This is a code-golf, so shortest code wins.
Example
n | d | sequence of maps
----+----+-----------------
1 | 3 | fgffgff
3 | 1 | fff
8 | 2 | ffff
1 | -3 | gfff
2 | 3 | fgfff
0 | 9 | [empty string]
1 | 1 | f
2 | 1 | ff
1 | -2 | gff
-1 | -2 | fgff
6 | 4 | ffgff
-2 | 3 | gffgff
8 | 9 | fgfffffffff