d = input() h = [] for i in xrange(3): h.append(input()) def mod_min(H): if H[1] != H[0] and H[1] != H[2] and min(H) == H[1]: print 0 return True diff = abs(H[1] - min(H[0], H[2])) H[1] -= (diff / d + 1) * d if H[1] != H[0] and H[1] != H[2] and min(H) == H[1]: #print "min" print H[1] return True return False def mod_max(H): if H[1] != H[0] and H[1] != H[2] and max(H) == H[1]: print 0 return True diff = abs(H[1] - max(H[0] ,H[2])) H[1] += (diff / d + 1) * d if H[1] != H[0] and H[1] != H[2] and max(H) == H[1]: #print "max" print H[1] return True return False def bad(): print -1 return True mod_min(h[:]) or mod_max(h[:]) or bad()