Remove repeated code from math