Instead of casting the double to an int in the (int) pow((double)a, (double)b) line, try rounding the results of pow, and then cast to int if necessary.
It's probably one of those floating point problem when you truncate, especially if your result's off by one.