Extract the mod into a function

mod doesn't work as expected for negatives
rem is remainder