Finding the smallest value with remainders