Harryxun/stf_run huggingface dataset:
import sys
x,y=map(int,input().split())
ans=1
i=1
while ans<=10**18:
  ans=i*x
  if ans%y=!0
    print(ans)
    sys.exit()
  i+=1
print(-1)


### FIXED CODE ###

x,y=map(int,input().split())
if x%y==0:
  print(-1)
else:
  print(x)
h, w, m = map(int, input().split())
dp= [[0]*w for i in range(h)]
dpcol = [0]*w
dprow = [0]*h
ypos = []
xpos = []
anscol = 0
ansrow = 0
ans = 0

for i in range(m):
    H, W = map(lambda x: int(x) - 1, input().split())
    dp[H][W] = 1
    dpcol[W] += 1
    dprow[H] += 1

for i in range(w): #列の最大値
    if dpcol[i] > anscol:
        anscol = dpcol[i]
        xpos = [i]
    elif dpcol[i] == anscol:
        xpos.append(i)

for i in range(h):
    if dprow[i] > ansrow:
        ansrow = dprow[i]
        ypos = [i]
    elif dprow[i] == ansrow:
        ypos.append(i)

for i in range(len(ypos)):
    for j in range(len(xpos)):
        if dp[ypos[i]][xpos[j]] == 1:
            ans = anscol + ansrow - 1
        else:
            ans = anscol + ansrow
            print(ans)
            exit()
print(ans)

### FIXED CODE ###

import sys
input = sys.stdin.readline

h, w, m = map(int, input().split())
col = [0]*w
row = [0]*h
ypos = []
xpos = []
bomb = []

for i in range(m):
    H, W = map(lambda x: int(x) - 1, input().split())
    col[W] += 1
    row[H] += 1
    bomb.append((H, W))

maxcol = max(col)
maxrow = max(row)

xpos = [h for h, x in enumerate(col) if x == maxcol]
ypos = [w for w, y in enumerate(row) if y == maxrow]

ans = maxcol + maxrow - 1
bomb = set(bomb)

for i in ypos:
    for j in xpos:
        if (i, j) not in bomb:
            ans += 1
            print(ans)
            exit()
print(ans)
from collections import Counter

N = int(input())
As = list(map(int, input().split()))
Bs = list(map(int, input().split()))

As_counter = Counter(As)
Bs_counter = Counter(Bs)

A_indices = dict()
for i, A in enumerate(As):
    if A in A_indices:
        A_indices[A].append(i)
    else:
        A_indices[A] = [i]
B_indices = dict()
for i, B in enumerate(Bs):
    if B in B_indices:
        B_indices[B].append(i)
    else:
        B_indices[B] = [i]

all_count = sorted((As_counter + Bs_counter).items(), key=lambda t: t[1], reverse=True)

if all_count[0][1] > N:
    print("No")
else:
    print("Yes")
    filling_order = []
    for elem, count in all_count[1:]:
        filling_order += A_indices[elem]
    filling_order += A_indices[all_count[0][0]]

    index = 0
    ans = [0] * N
    for elem, _ in all_count:
        count = Bs_counter[elem]
        for i in range(index, index + count):
            ans[filling_order[i]] = elem
        index += count

    print(*ans)
    assert not any(a == b for a, b in zip(ans, As))

### FIXED CODE ###

# Rotationによる解。
from collections import Counter

N = int(input())
As = list(map(int, input().split()))
Bs = list(map(int, input().split()))

elem_max_count = max((Counter(As) + Counter(Bs)).values())
if elem_max_count > N:
    print("No")
    exit()

# Bs[-index:] > As[:index] を満たすようなindexを二分探索
# 参考: https://twitter.com/catupper/status/1305163805802917889?s=20

ok = 0
ng = N + 1
while ng - ok > 1:
    mid = (ok + ng) // 2
    isok = True
    for b, a in zip(Bs[-mid:], As[:mid]):
        if b <= a:
            isok = False
            break
    
    if isok:
        ok = mid
    else:
        ng = mid

print("Yes")
print(*(Bs[-ok:] + Bs[:-ok]))
a = 0
n = int(N)
for i in range(1,n+1):
    if i % 5 != 0 and i % 3 != 0:
        a = a + i
    else:
        continue
return(a)

### FIXED CODE ###

a = 0
N = input()
n = int(N)
for i in range(1,n+1):
    if i % 5 != 0 and i % 3 != 0:
        a = a + i
    else:
        continue
print(a)
# -*- coding: utf-8 -*-
"""
Created on Tue Jun 30 09:18:42 2020

@author: Aruto Hosaka
"""
from math import factorial

def comb(n,k,p):
  """power_funcを用いて(nCk) mod p を求める"""
  if n<0 or k<0 or n<k: return 0
  if n==0 or k==0: return 1
  a=factorial(n) %p
  b=factorial(k) %p
  c=factorial(n-k) %p
  return (a*power_func(b,p-2,p)*power_func(c,p-2,p))%p
def power_func(a,b,p):
  """a^b mod p を求める"""
  if b==0: return 1
  if b%2==0:
    d=power_func(a,b//2,p)
    return d*d %p
  if b%2==1:
    return (a*power_func(a,b-1,p ))%p


A = list(map(int, input().split()))
mod = 998244353
N = A[0]
M = A[1]
K = A[2]

s = (M*(M-1)**(N-1))
D = (M*(M-1)**(N-1))%mod
for k in range(1,K+1):
    s = s*(N-k)//k//(M-1)
    D += s%mod

print(D%mod)

### FIXED CODE ###

mod=998244353
fact=[1]
for i in range(1,2*10**5+1): #mod上での階乗を求める
 fact.append((fact[-1]*i)%mod)
revfact=[1]
for i in range(1,2*10**5+1): #mod上での階乗の逆元をフェルマーの小定理を用いて求める
 revfact.append(pow(fact[i],mod-2,mod))
n,m,k=map(int,input().split())
ans=0
for i in range(k,-1,-1): #各m(N-K<=m<=N)について場合の数を求める
 group=n-i
 tmp=fact[n-1]*revfact[group-1]*revfact[n-1-(group-1)]
 tmp%=mod
 tmp*=m
 tmp%=mod
 tmp*=pow(m-1,group-1,mod)
 ans+=tmp
 ans%=mod
print(ans)
def bfs(linkL, chckL, nextNL, breath):
    pasNL = []
    for item in nextNL:
        # print(item, breath)
        chckL[item] = breath

    for item in nextNL:
        for lnkItem in linkL[item]:
            # linkL[lnkItem].remove(item)
            if (chckL[lnkItem] == -1) and (lnkItem not in pasNL):
                pasNL.append(lnkItem)
        # linkL[item] = []
    
    if len(pasNL) == 0:
        return chckL
    else:
        chckL = bfs(linkL, chckL, pasNL, breath+1)
        return chckL

N, X, Y = map(int, input().split())

lList = []

for indx in range(N):
    tmpList = []
    if indx != 0:   tmpList.append(indx-1)
    if indx != N-1: tmpList.append(indx+1)
    if indx == X-1: tmpList.append(Y-1)
    if indx == Y-1: tmpList.append(X-1)
    lList.append(tmpList)

mySum = [0] * (N-1)

for baseIndx in range(N):
    chckList = [-1] * N

    chckList = bfs(lList, chckList, [baseIndx], 0)
    chckList = chckList[baseIndx+1:N]

    for sumIndx in range(N-1):
        mySum[sumIndx] += chckList.count(sumIndx+1)

for printIndx in range(N-1):
    print(mySum[printIndx])



### FIXED CODE ###

N, X, Y = map(int, input().split())

X = X-1
Y = Y-1

kDict = {}

for kIndx in range(1, N+1):
    kDict[kIndx] = 0

for jIndx in range(N):
    for iIndx in range(jIndx):
        if (jIndx <= X) or (iIndx >= Y):
            kDict[jIndx - iIndx] += 1
        elif (iIndx <= X) and (jIndx >= Y):
            kDict[(jIndx - iIndx) - (Y - X - 1)] += 1
        elif (iIndx <= X) and ((jIndx > X) and (jIndx < Y)):
            if 2 * jIndx - (X + Y) - 1 > 0:
                kDict[(jIndx - iIndx) - (2 * jIndx - (X + Y) - 1)] += 1
            else:
                kDict[jIndx - iIndx] += 1
        elif ((iIndx > X) and (iIndx < Y)) and (jIndx >= Y):
            if (X + Y) - 2 * iIndx - 1 > 0:
                kDict[(jIndx - iIndx) - ((X + Y) - 2 * iIndx - 1)] += 1
            else:
                kDict[jIndx - iIndx] += 1
        else:
            if (2 * (jIndx - iIndx) - (Y - X) - 1) > 0:
                kDict[(jIndx - iIndx) - (2 * (jIndx - iIndx) - (Y - X) - 1)] += 1
            else:
                kDict[jIndx - iIndx] += 1

for kIndx in range(1, N):
    print(kDict[kIndx])
n = int(input())
ans = [[] for _ in range(2**(n-1))]

ans[0].append([1])
ans[1].append([1,1])
ans[1].append([1,2])
#ans[2].append([1,1,1])
#ans[2].append([1,1,2])
#ans[2].append([1,2,2])
#ans[2].append([1,2,3])
import numpy as np

for i in range(2, n):
    for j in range(2):
        for ai in ans[i-1]:
            x = np.array(ai)
            y = list(x+j)
            ans[i].append([1] + y)

r = ['a','b','c','d','e','f','g','h','i','j','k']
for ai in ans[n-1]:
    print(''.join(map(lambda x: str(r[x-1]), ai)))




### FIXED CODE ###

n = int(input())

ans = []
def dfs(x):
    if len(x) == n:
        ans.append(x)
        return
    for i in range(0, max(x)+1):
        y = x.copy()
        y.append(i+1)
        dfs(y)
dfs([1])
#print(ans)

r = ['a','b','c','d','e','f','g','h','i','j']
for ai in ans:
    print(''.join(map(lambda x: str(r[x-1]), ai)))
n,m=map(int,input())
 
l=-1
r=10**6
 
for _ in range(m):
  il, ir=map(int,input())
  l=max(l,il)
  r=min(r,ir)
  
print(max(0,r-l+1))

### FIXED CODE ###

n,m=map(int,input().split())
 
l=-1
r=10**6
 
for _ in range(m):
  il, ir=map(int,input().split())
  l=max(l,il)
  r=min(r,ir)
  
print(max(0,r-l+1))
# 入力
N = int(input())
H = [int(i) for i in input().split()]

# メモ用のDPテーブルを生成
dp = [float("inf") for i in range(N)]

# 足場iにたどり着く最初コストを返す
def rec(i):
    # ベースケースをセット
    if i == 0:
        return 0
    
    # メモをチェック
    if dp[i] < float("inf"):
        return dp[i]
    
    # i-1から遷移する場合
    cost = rec(i-1) + abs(H[i] - H[i-1])
    # i-2から遷移する場合
    if i > 1:
        cost = min(cost, rec(i-2) + abs(H[i] - H[i-2]))
    
    # 結果をメモしてから返す
    dp[i] = cost
    return cost

print(rec(N-1))

### FIXED CODE ###

# 最小値に置き換える関数
def chmin(a, b):
    if a > b:
        a = b
        return True
    
    return False

# 入力
N = int(input())
H = [int(i) for i in input().split()]

# dpテーブルの生成
dp = [float("inf") for i in range(N)]
# 初期条件のセット(足場1)
dp[0] = 0

# N番目の足場までのループ
# i = 1のときはi-2がないことに注意
for i in range(N):
    # ノードi-1からの遷移を計算
    dp[i] = min(dp[i], dp[i-1]+abs(H[i] - H[i-1]))
    if i > 1:
        dp[i] = min(dp[i], dp[i-2]+abs(H[i] - H[i-2]))

# dpテーブルの末尾が答え
print(dp[N-1])
h,w,n=[input() for i in range(3)]
n = int(n)
w = int(w)
h = int(h)
if(h >= w):
  temp = h
elif(w > h):
  temp = w
temp = (n // temp)
if(n % temp != 0):
    temp = temp + 1
print(temp)

### FIXED CODE ###

h,w,n=[input() for i in range(3)]
n = int(n)
w = int(w)
h = int(h)
if(h >= w):
  temp = h
elif(w > h):
  temp = w
if(n % temp != 0):
  temp = (n // temp)
  temp = temp + 1
else:
  temp = (n // temp)
print(temp)
N = int(input())
A = list(map(int, input().split()))

lim = 1
for i in range(18):
    lim *= 10

ans = 1

for A_ in A:
    ans *= A
    if ans > lim:
        ans = -1
        break

print(ans)


### FIXED CODE ###

N = int(input())
A = list(map(int, input().split()))

l = 1
for i in range(18):
    l *= 10

ans = 1

for A_ in A:
    ans *= A_
    if ans > l:
        ans = -1
        break

if 0 in A: ans = 0

print(ans)
a=input()
b=a**3
print(b)

### FIXED CODE ###

a=int(input())

b=a**3
print(b)
N,M = map(int, input().split())

P = [list(map(int,input().split())) for i in range(M)]
s=[]
c=[]

for i in range(M):
    s.append(P[i][0])
    c.append(P[i][1])
A=[-1]*N

k=0
for i in range (M):
    if (A[s[i]-1]==-1) or (A[s[i]-1]==c[i]):
        A[s[i]-1]=c[i]
    else:
        k=1
        print(-1)
aa=0
if A[0]==0:
    k=1
    print(-1)
if k==0:
    for i in range (M):
        if A[i]==-1:
            A[i] = 0
        aa+=A[i]*pow(10,(M-i-1))

    print(aa)

### FIXED CODE ###

N,M = map(int, input().split())

P = [list(map(int,input().split())) for i in range(M)]
s=[]
c=[]

for i in range(M):
    s.append(P[i][0])
    c.append(P[i][1])
A=[-1]*N

k=0
for i in range (M):
    if (A[s[i]-1]==-1) or (A[s[i]-1]==c[i]):
        A[s[i]-1]=c[i]
    else:
        k=1
        print(-1)
aa=0
if A[0]==0 and N>1:
    k=1
    print(-1)
if M==0:
    k=1
    if N==1:
        print(0)
    else:
        print(pow(10,(N-1)))

if k==0:
    for i in range (N):
        if A[i]==-1:
            A[i] = 0
            if A[0]==0:
                A[0]=1

        aa+=A[i]*pow(10,(N-i-1))

    print(aa)
N, K = map(int, input().split())
P = [int(i) - 1 for i in input().split()]
Q = [int(i) for i in input().split()]
ans = - 10000000000
for i in range(N):
    tmp = []
    now = i
    cnt = 0
    for j in range(1, N + 1):
        now = P[now]
        cnt += Q[now]
        tmp.append(cnt)
        if now == i:
            break
    ans = max(ans, max(tmp[:K]))
    else:
        v = (tmp[-1] * (K // j))
        if K % j > 0:
            v += max(tmp[:(K % j)])
        ans = max(ans, v)
print(ans)

### FIXED CODE ###

N, K = map(int, input().split())
P = [int(i) - 1 for i in input().split()]
Q = [int(i) for i in input().split()]
ans = - float('inf')
for i in range(N):
    now = i
    cnt = 0
    span = 0
    while True:
        span += 1
        cnt += Q[now]
        now = P[now]
        if now == i:
            break
    point = 0
    now = i
    for j in range(1, span + 1):
        point += Q[now]
        now = P[now]       
        if j > K:
            break
        value = point + (max(cnt, 0) * ((K - j) // span))
        ans = max(ans, value)
print(ans)
# D
import numpy as np
N = int(input())
X = np.zeros(N, dtype=int)
Y = np.zeros(N, dtype=int)

for i in range(N):
    x, y = map(int, input().split())
    X[i] = x
    Y[i] = y

# edges
X_s = np.argsort(X)
Y_s = np.argsort(Y)

edge_list = []
edge_weight = []
for i in range(N-1):
    edge_list.append([X_s[i], X_s[i+1]])
    edge_weight.append(min(abs(X[X_s[i+1]] - X[X_s[i]]), abs(Y[X_s[i+1]] - Y[X_s[i]])))
    edge_list.append([Y_s[i], Y_s[i+1]])
    edge_weight.append(min(abs(X[Y_s[i+1]] - X[Y_s[i]]), abs(Y[Y_s[i+1]] - Y[Y_s[i]])))
    
# sort edges
sel = np.argsort(np.array(edge_weight))

# union find tree
uf = dict()
for i in range(N):
    uf[i] = i

res = 0
flg = np.zeros(N)

for s in sel:
    m, n = edge_list[s]
    # find union
    gr_m = m
    gr_m_list = []
    gr_n = n
    gr_n_list = []
    while gr_m != uf[gr_m]:
        gr_m_list.append(gr_m)
        gr_m = uf[gr_m]
    for m_ in gr_m_list:
        uf[m_] = gr_m
        
    while gr_n != uf[gr_n]:
        gr_n_list.append(gr_n)
        gr_n = uf[gr_n]
        
    for n_ in gr_n_list:
        uf[n_] = gr_n
    if gr_m == gr_n:
        pass
    else:
        res += edge_weight[s]
        if dep_m > dep_n:
            uf[gr_n] = gr_m
        elif dep_m > dep_n:
            uf[gr_n] = gr_m
        else:
            uf[gr_m] = gr_n
print(res)

### FIXED CODE ###

# D
import numpy as np
N = int(input())
X = []
Y = []

for i in range(N):
    x, y = map(int, input().split())
    X.append(x)
    Y.append(y)

# edges
X_s = np.argsort(np.array(X))
Y_s = np.argsort(np.array(Y))

edge_list = []
edge_weight = []
for i in range(N-1):
    edge_list.append([X_s[i], X_s[i+1]])
    edge_weight.append(X[X_s[i+1]] - X[X_s[i]])
    edge_list.append([Y_s[i], Y_s[i+1]])
    edge_weight.append(Y[Y_s[i+1]] - Y[Y_s[i]])
    
# sort edges
sel = np.argsort(np.array(edge_weight))

# union find tree
uf = np.arange(N)


res = 0
flg = np.zeros(N)

for s in sel:
    m, n = edge_list[s]
    # find union
    gr_m = m
    gr_m_list = []
    gr_n = n
    gr_n_list = []
    while gr_m != uf[gr_m]:
        gr_m_list.append(gr_m)
        gr_m = uf[gr_m]
    for m_ in gr_m_list:
        uf[m_] = gr_m
        
    while gr_n != uf[gr_n]:
        gr_n_list.append(gr_n)
        gr_n = uf[gr_n]
    for n_ in gr_n_list:
        uf[n_] = gr_n
        
    if gr_m == gr_n:
        pass
    else:
        res += edge_weight[s]
        uf[gr_n] = gr_m
print(res)
n,m = [int(i) for i in input().split()]
a = list(map(int,input().split()))


match = [0,2,5,5,4,5,6,3,7,6]

dig = [0] * (n+1)

inf = 10**9


for i in range(1, n + 1):
    lst = []
    for j in range(len(a)):
        num = a[j]
        mat = match[num]
        bef = i - mat
        if bef >= 0:
            if bef == 0:
                lst.append(dig[bef])
            else:
                if dig[bef] > 0:
                    lst.append(dig[bef])
        if lst:
            dig[i] = max(lst) + 1


ans = ""


def dp(i):
    k = -1
    if i == 0:
        return
    global ans
    maxi = 0
    for j in range(len(a)):
        num = a[j]
        mat = match[num]
        bef = i - mat
        if dig[i] == 1:
            if bef == 0:
                maxi = max(maxi, num)
                k = 0
        else:
            if bef >= 0:
                if dig[bef] == dig[i] - 1:
                    if num > maxi:
                        maxi = num
                        k = bef
    ans += str(maxi)
    if k >= 0:
        dp(k)


dp(n)
print(ans)

### FIXED CODE ###

n,m = [int(i) for i in input().split()]
a = list(map(int,input().split()))

import sys
sys.setrecursionlimit(50000)

match = [0,2,5,5,4,5,6,3,7,6]

dig = [0] * (n+1)

inf = 10**9


for i in range(1, n + 1):
    lst = []
    for j in range(len(a)):
        num = a[j]
        mat = match[num]
        bef = i - mat
        if bef >= 0:
            if bef == 0:
                lst.append(dig[bef])
            else:
                if dig[bef] > 0:
                    lst.append(dig[bef])
        if lst:
            dig[i] = max(lst) + 1


ans = ""


def dp(i):
    k = -1
    if i == 0:
        return
    global ans
    maxi = 0
    for j in range(len(a)):
        num = a[j]
        mat = match[num]
        bef = i - mat
        if dig[i] == 1:
            if bef == 0:
                maxi = max(maxi, num)
                k = 0
        else:
            if bef >= 0:
                if dig[bef] == dig[i] - 1:
                    if num > maxi:
                        maxi = num
                        k = bef
    ans += str(maxi)
    if k >= 0:
        dp(k)


dp(n)
print(ans)
def f(s, cost, route, ans):
    route.append(s)
    ans += cost[s]
    del cost[s]
    for k, c in data.items():
            if s in k:
                a, b = k
                a, b = a, b if s == a else b, a
                if not b in route:
                    if not b in cost or c < cost[b]:
                        cost[b] = c
                        del data[(a, b)]
    if cost:
        s = sorted(cost.items(), key=lambda x: x[1])[0][0]
        return f(s, cost, route, ans)
    return ans

while 1:
    n, m = map(int, raw_input().split())
    if n == m == 0: break
    data = {}
    for i in range(m):
        a, b, c = map(int, raw_input().split())
        data[(a, b)] = c
    print f(0, {0:0}, [], 0)

### FIXED CODE ###

def f(s, cost, route, ans):
    route.append(s)
    ans += cost[s]
    del cost[s]
    for k, c in data.items():
        if s in k:
            a, b = k
            if s == a:
                if not b in route:
                    if not b in cost or c < cost[b]:
                        cost[b] = c
                        del data[(a, b)]
            elif s == b:
                if not a in route:
                    if not a in cost or c < cost[a]:
                        cost[a] = c
                        del data[(a, b)]
    if cost:
        s = sorted(cost.items(), key=lambda x: x[1])[0][0]
        return f(s, cost, route, ans)
    return ans

while 1:
    n, m = map(int, raw_input().split())
    if n == m == 0: break
    data = {}
    for i in range(m):
        a, b, c = map(int, raw_input().split())
        data[(a, b)] = c
    print f(0, {0:0}, [], 0)
n=int(input())
if n<6:print(int(n>2));quit()
M=10**9+7
ln,hn,dp=n-6,n-5,2
s=0
n,d=n-5,1
while n:
  for i in range(3):n=(n*ln)%M;ln-=1
  for i in range(2):n=(n*pow(hn,-1,M))%M;hn-=1
  d=(d*pow(dp,-1,M))%M,dp+=1
  s=(s+n*d)%M
print(s)

### FIXED CODE ###

n=int(input())
if n<7:print(n//3);quit()
M=10**9+7
ln,hn,dp=n-6,n-5,2
s=n-4
n,d=n-5,1
while n:
  for i in range(3):n=(n*ln)%M;ln-=1
  for i in range(2):n=(n*pow(hn,-1,M))%M;hn-=1
  d=(d*pow(dp,-1,M))%M;dp+=1
  s=(s+n*d)%M
print(s)
I = input("")
i = I.split("\n")

N = int(i[0])
l = []
t = 0

for k in range(N):
    if i[k+1] not in l:
        l.append(i[k+1])
        t = t+1
print(len(l))


### FIXED CODE ###

N = int(input(""))
M = []
n = 0

for i in range(N):
    p = input("")
    M.append(p)

Mm = list(set(M))

print(len(Mm))
n = int(input())
x = [int(i) for i in input().split()]

for i in range(n):
    a = x[:]
    del a[i]
    a.sort()
    print(a[(n-1)/2-1])


### FIXED CODE ###

n = int(input())
x = [int(i) for i in input().split()]
a = x[:]
a.sort()

mid = n //2
m1 = a[mid-1]
m2 = a[mid]
for i in range(n):
    if x[i] <= m1:
        ans = m2
    else:
        ans = m1
 
    print(ans)
N = int(input())
max = 0

init = list(range(1, N+1))
all = []
hashtable = {}
tempSum = 0


def helper(input):
    global tempSum, max
    if len(input) == N:
        # print(input)
        if tempSum > max:
            max = tempSum
        return

    for i in range(1, N+1):
        if i not in input:
            input.append(i)
            tempSum += len(input) % i
            # print(tempSum, len(input), i)
            helper(input)
            input.pop()
            tempSum -= len(input) % i


list = []
helper(list)

print(max)


### FIXED CODE ###

N = int(input())
max = 0


print((N-1)*N//2)
import sys

sys.setswitchinterval(10**8)


next_s = ((-1, 1), (0, 1), (1, 1),
          (-1, 0), (1, 0),
          (-1, -1), (0, -1), (1, -1))


def DFS(x, y):
    if not (0 <= x < W and 0 <= y < H):
        return
    if not map_[y * W + x]:
        return

    map_[y * W + x] = 0

    for dx, dy in next_s:
        DFS(x + dx, y + dy)


while True:
    W, H = map(int, input().split())
    if W == 0 and H == 0:
        break

    map_ = []
    for h in range(H):
        map_ += list(map(int, input().split()))
    island_num = 0
    while any(map_):
        next_idx = map_.index(1)
        x = next_idx % W
        y = next_idx // W
        DFS(x, y)
        island_num += 1

    print(island_num)



### FIXED CODE ###

#!python
# -*- coding: utf-8 -*-

import sys

sys.setrecursionlimit(10**6)


next_s = ((-1, 1), (0, 1), (1, 1),
          (-1, 0), (1, 0),
          (-1, -1), (0, -1), (1, -1))


def DFS(x, y):
    if not (0 <= x < W and 0 <= y < H):
        return
    if map_[y][x] == 0:
        return

    map_[y][x] = 0

    for dx, dy in next_s:
        DFS(x + dx, y + dy)


while True:
    W, H = map(int, input().split())
    if W == 0 and H == 0:
        break
    map_ = [list(map(int, input().split())) for h in range(H)]
    island_num = 0
    for x in range(W):
        for y in range(H):
            if map_[y][x] == 1:
                DFS(x, y)
                island_num += 1
    print(island_num)
W, H = map(int, input().split())
L = [input() for _ in range(H)]

count = 0
for i in range(H):
  for j in range(W):
    if L[i][j] == '#':
      count += 1
      
if count == W + H - 1:
  print('Possible')
else:
  print('Impossible')

### FIXED CODE ###

H, W = map(int, input().split())
L = [input() for _ in range(H)]

count = 0
for i in range(H):
  for j in range(W):
    if L[i][j] == '#':
      count += 1
      
if count == W + H - 1:
  print('Possible')
else:
  print('Impossible')
import sys
from functools import lru_cache
N, M = map(int, input().split())
ok = [True] * (N + 1)
for _ in range(M):
    a = int(sys.stdin.readline())
    ok[a] = False
sys.setrecursionlimit(N + 100)
@lru_cache(maxsize=None)
def f(s):
    if not ok[s]:
        return 0
    if s in (0, 1, 2):
        return s
    count = f(s - 1) + f(s - 2)
    count %= 1000000007
    return count

ans = f(N)
print(ans)

### FIXED CODE ###

import sys
N, M = map(int, input().split())
ok = [True] * (N + 1)
for _ in range(M):
    a = int(sys.stdin.readline())
    ok[a] = False
ans = 0
if N == 1:
    ans = 1
else:
    counts = [0] * (N + 1)
    if ok[1]:
        counts[1] = 1
    if ok[2]:
        counts[2] = counts[1] + 1
    for s in range(3, N + 1):
        if ok[s]:
            count = counts[s-1] + counts[s-2]
            count %= 1000000007
            counts[s] = count
    ans = counts[N]
print(ans)
while True:
	ints = raw_input()
	if ints != '':
		x = map(int,ints.split(' '))
		x.sort()
		a = x[1]
		b = x[0]
		while True:
			m=a%b
			if m!=0:
				a=b
				b=m
				continue
			else:
				break
		n = x[1]*x[0]/b
	print b,n

### FIXED CODE ###

while True:
	try:
		while True:
			ints = raw_input()
			if ints != '':
				x = map(int,ints.split(' '))
				x.sort()
				a = x[1]
				b = x[0]
				while True:
					m=a%b
					if m!=0:
						a=b
						b=m
						continue
					else:
						break
				n = x[1]*x[0]/b
				print b,n
				continue
			else:
				break
	except: break
a,b=map(int,input().split())
c=[]
for i in range(a,b+1):
  for j in range(i):
    d=(i*j)%2019
    c.append(d)
print(min(d))


### FIXED CODE ###

a,b=map(int,input().split())
if b-a>=2019:
    print(0)
    exit()
d=[]
for i in range(a,b+1):
    if i%2019==0:
        print(0)
        exit()
    for j in range(a,b+1):
        if i<j:
            d.append((i*j)%2019)
print(min(d))
N,M = map(int,input().split())
L = list(map(int,input().split()))
R = list(map(int,input().split()))
L.sort()
R.sort()
count = 0
for i in range(1,N+1):
  if i >= L[-1] and i <= R[0]:
    count += 1
print(count)

### FIXED CODE ###

N,M = map(int,input().split())
L = []
R = []
ans = 0
for _ in range(M):
  l, r = map(int, input().split())
  L.append(l)
  R.append(r)
ans = max(0,min(R) - max(L) + 1)
print(ans)