The logic in both branches looks like it can be handled by divison and modulo. Is there any reason why this is not done?