Let's say I have an integer position $p$ inside some integer range $r$, such that
$$ 0 \le p < r \;\;\;\textrm{with}\;p, r \in \mathbb{N} $$
I need to scale a position $p$ from a small range where $0<r<2^{31}$ to the corresponding position $P$ in a big range $0<R<2^{63}$ and back (in programming terms: I have one scenario where my position and range are 32-bit integers and another where my position and range are 64-bit integers).
So, essentially all I need to do is:
$$ P = \lfloor \, p * R / r\rfloor\;\;\;\;\;\textrm{and}\;\;\;\;\ p = \lfloor P * r / R \rfloor $$ But, for this transformation, I am only allowed to perform 64-bit integer operations.
To scale the small range up to the big range without generating overflows or rounding errors is relatively easy:
$$ P = \lfloor \, p * R / r\rfloor = \lfloor R / r\rfloor * p + \lfloor((R\bmod{r} ) * p) / r\rfloor $$ (I used $\lfloor\cdot\rfloor$ to indicate the implicit rounding of the integer division operations)
Aside - a quick explanation of the reasoning behind this equation: Since $p<r$, the first term in the sum will never exceed $2^{63}$. But, doing the division "first" to make this happen, leads to a rounding error. This error is captured by the modulus operation in the second term, which, since $p<r<2^{31}$, can also not exceed $2^{63}$. Thus, this formula allows me to calculate $P$ such that it is correctly rounded down to the nearest integer, only using integer arithmetic with numbers $<2^{63}$.
What I'm having some difficulty with is finding the reverse formula, i.e. for $p = \lfloor P * r / R \rfloor$:
I'm looking for a function $f(P, r, R)$ that calculates $\lfloor P * r / R \rfloor$ while only using 64-bit integer arithmetic, i.e. every division implies an immediate rounding down and all intermediate values must fall within the range $[{-\,2^{63}, +\,2^{63}}[$.
UPDATE:
I've been playing with a recursive solution by partially solving the reverse equation for $p$:
$$ P = \lfloor R/r \rfloor * p + \lfloor ((R\bmod{r})*p)/r \rfloor $$
$$ \lfloor R/r \rfloor * p_{n+1} = P - \lfloor ((R\bmod{r})*p_n)/r \rfloor $$
$$ p_{n+1} = \bigg\lfloor \frac{P}{\lfloor R/r \rfloor} \bigg\rfloor - \bigg\lfloor \frac{\lfloor ((R\bmod{r})*p_n)/r \rfloor} {\lfloor R/r \rfloor} \bigg\rfloor $$
For most values of $r$, $P$, and $R$ it very quickly gives a value that is within $\pm 1$ of the actual answer. But sometimes, it ends up oscillating between two consecutive values and if $R\bmod{r}$ becomes much larger than $R/r$, convergence is either really slow, or sometimes doesn't happen at all.
Can this be improved somehow to guarantee quick convergence to the actual answer? Or maybe it's possible to make this non-recursive?