def extgcd(a, b): # ax + by = gcd(a,b) # return gcd(a,b), x, y if a == 0: return b, 0, 1 else: g, x, y = extgcd(b % a, a) return g, y - (b // a) * x, x def chineseRem(b1, m1, b2, m2): # x ≡ b1 (mod m1) ∧ x ≡ b2 (mod m2) <=> x ≡ r (mod m) # となる(r. m)を返す # 解無しのとき(0, -1) if (b1,m1) == (0,1): return b2,m2 if (b2,m2) == (0,1): return b1,m1 d, p, q = extgcd(m1, m2) if (b2 - b1) % d != 0: return 0, -1 m = m1 * (m2 // d) # m = lcm(m1, m2) tmp = (b2-b1) // d * p % (m2 // d) r = (b1 + m1 * tmp) % m return r, m n = int(input()) m = int(input()) x,y = 0,1 for _ in range(m): b,c = map(int,input().split()) c %= b x,y = chineseRem(x,y,c,b) # print(x,y,b,c) if y == -1 or x > n: print("NaN") exit() if x <= n: print(x) else: print("NaN")