I've been trying to implement Pollard's Rho recently. The original idea was to implement the code in several languages and put it up for everyone to see for educational purposes. I first took to Wikipedia and implemented the code from Pollard's rho algorithm for logarithms. I translated the code directly from C++ to Haskell and it generated the same output as C++ so I was happy. It agreed with the example in the Wikipedia page. However, when taking the output and solving $(B - b)\ \gamma \equiv (a - A)\pmod n$, I got results that were different than what the logarithm should be. If you would like to comment on this code, comment on the C++ code in the Wikipedia article please, I guess that's the most accessible version.
Unhappy with the Wikipedia article I searched further and found a gist with Python code that's based on Algorithm 3.60 in the Handbook of Applied Cryptography, linked in the gist. This version could calculate the logarithm for the example mentioned in the code (taken from the book). It yields different results to the code from the Wikipedia page. I have verified, and the Python code reads exactly like the algorithm is described in the book. However, if I feed it something like $n=6,\ Z=7,\ alpha=5,\ beta=4$ then obviously the $dlog$ of $4$ to the base of $5$ in $\mathbb{Z}_7^*$ should be $2$, because $5^2\pmod 7 \equiv 25\pmod 7 \equiv 4 \pmod 7$. But instead it breaks down with an exception, because it tries to get the inverse of $4\pmod 6$, and obviously there isn't one, because $gcd(4, 6) = 2 \neq 1$. It does that because in the last step of the algorithm, described on print page 106, it will arrive at $r = b_i - b_{2i} = 4$ and it has to compute $r^{-1}$. HAC is supposed to be a respectable book, but the code I have yields bad results, so am I doing something wrong? Is the book wrong?
I've spent a few days on this now. And yes, I've read through this stack exchange searching for Pollard's Rho. How do I fix this code? Why does the Python and C++ code break down? Is there a version of Pollard's Rho algorithm that generally just works other than for a few select cases? Is there a book that describes such an algorithm? Can someone point me to a working version?