def extgcd(a, b): if b: d, y, x = extgcd(b, a % b) y -= (a // b) * x return d, x, y return a, 1, 0 # V = [(X_i, Y_i), ...]: X_i (mod Y_i) def remainder(V): x = 0; d = 1 for X, Y in V: g, a, b = extgcd(d, Y) x, d = (Y*b*x + d*a*X) // g, d*(Y // g) x %= d return x, d N = int(input()) M = int(input()) V = [] for i in range(M): B,C = map(int,input().split()) C %= B V.append([C,B]) x,d = remainder(V) if x > N: print("NaN") exit(0) for C,B in V: if x % B != C: print("NaN") exit(0) print(x)