I think that you benefit from having a function that implements a variant of MOD where variant_MOD(i, j) returns a value in the range 1..j instead of 0..j-1 — when the value from MOD(i, j) would be 0, it returns j instead. Ignoring negative values, this jmod() does the job: