Optimize powers of 3 computations.

Also some code cleanup.