The loop needs to continue until $val is less than `$rem`, not until it's outside the `$rem`