Modulo (%) not calculating correctly

The pow function isn't doing what you'd expect. It only gives correct results when x=0 or 1. For example, the result of pow(10,3) is not 1000, it is 999.
You'll be better off calculating the powers yourself.

Pete