Mathematics x Programming Competition #8 - General Solution