In reply to Ian Wakeling.

Thanks, Ian! I programmed it the way I did because that's the way that it was constructed in Moler's book. In MATLAB mod(a,q) is always positive when q>0, so I wrote the helper funtion to mimic the MATLAB mod() function. But you're right: in practice there is no need for the helper function.