CodeEff/ECCO huggingface dataset:
# Original solution
'''
    Auther: ghoshashis545 Ashis Ghosh
    College: jalpaiguri Govt Enggineering College

'''
from os import path
import sys
from functools import cmp_to_key as ctk
from collections import deque,defaultdict as dd 
from bisect import bisect,bisect_left,bisect_right,insort,insort_left,insort_right
from itertools import permutations
from datetime import datetime
from math import ceil,sqrt,log,gcd
def ii():return int(eval(input()))
def si():return eval(input())
def mi():return list(map(int,input().split()))
def li():return list(mi())
abc='abcdefghijklmnopqrstuvwxyz'
mod=1000000007
#mod=998244353
inf = float("inf")
vow=['a','e','i','o','u']
dx,dy=[-1,1,0,0],[0,0,1,-1]

def bo(i):
    return ord(i)-ord('a')

file = 0

def solve():
    



    # for _ in range(ii()):

    n=ii()
    n%=1000
    if n!=0:
        n=1000-n
    print(n)









  
















if __name__ =="__main__":

    if(file):

        if path.exists('input1.txt'):
            sys.stdin=open('input1.txt', 'r')
            sys.stdout=open('output1.txt','w')
        else:
            input=sys.stdin.readline
    solve()

# Optimized solution
'''
    Auther: ghoshashis545 Ashis Ghosh
    College: jalpaiguri Govt Enggineering College

'''
from os import path
import sys
from heapq import heappush,heappop
from functools import cmp_to_key as ctk
from collections import deque,defaultdict as dd 
from bisect import bisect,bisect_left,bisect_right,insort,insort_left,insort_right
from itertools import permutations
from datetime import datetime
from math import ceil,sqrt,log,gcd
def ii():return int(eval(input()))
def si():return eval(input())
def mi():return list(map(int,input().split()))
def li():return list(mi())
abc='abcdefghijklmnopqrstuvwxyz'
mod=1000000007
# mod=998244353
inf = float("inf")
vow=['a','e','i','o','u']
dx,dy=[-1,1,0,0],[0,0,1,-1]

def bo(i):
    return ord(i)-ord('a')

file=0





def solve():


    # for _ in range(ii()):
    
        

    n=ii()
    n%=1000
    if(n!=0):
        n=1000-n
    print(n)
 








        
if __name__ =="__main__":

    if(file):

        if path.exists('input1.txt'):
            sys.stdin=open('input1.txt', 'r')
            sys.stdout=open('output1.txt','w')
        else:
            input=sys.stdin.readline
    solve()
# Original solution
'''
    Auther: ghoshashis545 Ashis Ghosh
    College: jalpaiguri Govt Enggineering College

'''
from os import path
import sys
from heapq import heappush,heappop
from functools import cmp_to_key as ctk
from collections import deque,defaultdict as dd 
from bisect import bisect,bisect_left,bisect_right,insort,insort_left,insort_right
from itertools import permutations
from datetime import datetime
from math import ceil,sqrt,log,gcd
def ii():return int(eval(input()))
def si():return eval(input())
def mi():return list(map(int,input().split()))
def li():return list(mi())
abc='abcdefghijklmnopqrstuvwxyz'
mod=1000000007
# mod=998244353
inf = float("inf")
vow=['a','e','i','o','u']
dx,dy=[-1,1,0,0],[0,0,1,-1]

def bo(i):
    return ord(i)-ord('a')

file=0





def solve():


    # for _ in range(ii()):
    
        

    n=ii()
    n%=1000
    if(n!=0):
        n=1000-n
    print(n)
 








        
if __name__ =="__main__":

    if(file):

        if path.exists('input1.txt'):
            sys.stdin=open('input1.txt', 'r')
            sys.stdout=open('output1.txt','w')
        else:
            input=sys.stdin.readline
    solve()


# Optimized solution
'''
    Auther: ghoshashis545 Ashis Ghosh
    College: jalpaiguri Govt Enggineering College

'''
from os import path
import sys
from heapq import heappush,heappop
from functools import cmp_to_key as ctk
from collections import deque,defaultdict as dd 
from bisect import bisect,bisect_left,bisect_right,insort,insort_left,insort_right
from itertools import permutations
from datetime import datetime
from math import ceil,sqrt,log,gcd
def ii():return int(eval(input()))
def si():return eval(input())
def mi():return list(map(int,input().split()))
def li():return list(mi())
abc='abcdefghijklmnopqrstuvwxyz'
mod=1000000007
# mod=998244353
inf = float("inf")
vow=['a','e','i','o','u']
dx,dy=[-1,1,0,0],[0,0,1,-1]

def bo(i):
    return ord(i)-ord('a')

file=1





def solve():


    # for _ in range(ii()):
    
        

    n=ii()
    n%=1000
    if(n!=0):
        n=1000-n
    print(n)
 








        
if __name__ =="__main__":

    if(file):

        if path.exists('input1.txt'):
            sys.stdin=open('input1.txt', 'r')
            sys.stdout=open('output1.txt','w')
        else:
            input=sys.stdin.readline
    solve()
# Original solution
N = int(eval(input())) 

while N > 0:
  N = N - 1000

if N < 0:
  N = N * -1

print(N)

# Optimized solution
N = int(eval(input())) 
 
while N > 0:
  N -= 1000
 
if N < 0:
  N *= -1
 
print(N)
# Original solution
n = int(eval(input()))
if n%1000 == 0:
    print((0))
else:
    print((1000-n%1000))

# Optimized solution
n = int(eval(input()))
print(((1000-n%1000)%1000))
# Original solution
print(((1000 - int(eval(input())) % 1000) % 1000))

# Optimized solution
print((-int(eval(input())) % 1000))
# Original solution
a=int(eval(input()))
if a%1000==0:
  print((0))
else:
    print((1000-a%1000))

# Optimized solution
n=int(eval(input()))
n=n%1000
if n==0:
  print((0))
else:
  print((1000-n))
# Original solution
import sys

def I(): return int(sys.stdin.readline().rstrip())
def LI(): return list(map(int,sys.stdin.readline().rstrip().split()))
def S(): return sys.stdin.readline().rstrip()
def LS(): return list(sys.stdin.readline().rstrip().split())

N = I()

ans = N // 1000
ans2 = N - (ans*1000)

if ans2 == 0:
    print((0))
else:
    print((1000-ans2))

# Optimized solution
import sys

def I(): return int(sys.stdin.readline().rstrip())
def LI(): return list(map(int,sys.stdin.readline().rstrip().split()))
def S(): return sys.stdin.readline().rstrip()
def LS(): return list(sys.stdin.readline().rstrip().split())

N = I()

N %= 1000
if N==0:
    print((0))
else:
    print((1000-N))
# Original solution
# -*- coding: utf-8 -*-
# 標準入力を取得
N = int(eval(input()))

# 求解処理
ans = (1000 - (N % 1000)) % 1000

# 結果出力
print(ans)


# Optimized solution
# -*- coding: utf-8 -*-

def get_input() -> int:
    """
    標準入力を取得する.

    Returns:\n
        int: 標準入力
    """
    N = int(eval(input()))

    return N


def main(N: int) -> None:
    """
    メイン処理.

    Args:\n
        N (int): 整数（1 <= N <= 10000）
    """
    # 求解処理
    ans = (1000 - (N % 1000)) % 1000

    # 結果出力
    print(ans)


if __name__ == "__main__":
    # 標準入力を取得
    N = get_input()

    # メイン処理
    main(N)
# Original solution
N = int(eval(input()))
if N%1000 == 0:
    print((0))
else:
    print((1000-N%1000))

# Optimized solution
N = int(eval(input()))
print(((10000-N)%1000))
# Original solution
import sys
sys.setrecursionlimit(10**7) #再帰関数の上限,10**5以上の場合python
import math
from copy import copy, deepcopy
from copy import deepcopy as dcp
from operator import itemgetter
from bisect import bisect_left, bisect, bisect_right#2分探索
#bisect_left(l,x), bisect(l,x)#aはソート済みである必要あり。aの中からx未満の要素数を返す。rightだと以下
from collections import deque, defaultdict
#deque(l), pop(), append(x), popleft(), appendleft(x)
#q.rotate(n)で → にn回ローテート
from collections import Counter#文字列を個数カウント辞書に、
#S=Counter(l),S.most_common(x),S.keys(),S.values(),S.items()
from itertools import accumulate,combinations,permutations#累積和
#list(accumulate(l))
from heapq import heapify,heappop,heappush
#heapify(q),heappush(q,a),heappop(q) #q=heapify(q)としないこと、返り値はNone
#import fractions#古いatcoderコンテストの場合GCDなどはここからimportする
from functools import reduce,lru_cache#pypyでもうごく
#@lru_cache(maxsize = None)#maxsizeは保存するデータ数の最大値、2**nが最も高効率
from decimal import Decimal

def input(): 
    x=sys.stdin.readline()
    return x[:-1] if x[-1]=="\n" else x
def printe(*x):print("## ",*x,file=sys.stderr)
def printl(li): _=print(*li, sep="\n") if li else None
def argsort(s, return_sorted=False): 
    inds=sorted(range(len(s)), key=lambda k: s[k])
    if return_sorted: return inds, [s[i] for i in inds]
    return inds
def alp2num(c,cap=False): return ord(c)-97 if not cap else ord(c)-65
def num2alp(i,cap=False): return chr(i+97) if not cap else chr(i+65)
def matmat(A,B):
    K,N,M=len(B),len(A),len(B[0])
    return [[sum([(A[i][k]*B[k][j]) for k in range(K)]) for j in range(M)] for i in range(N)]
def matvec(M,v):
    N,size=len(v),len(M)
    return [sum([M[i][j]*v[j] for j in range(N)]) for i in range(size)]
def T(M):
    n,m=len(M),len(M[0])
    return [[M[j][i] for j in range(n)] for i in range(m)]
def main():
    mod = 1000000007
    #w.sort(key=itemgetter(1),reverse=True)  #二個目の要素で降順並び替え

    N = int(input())
    #N, K = map(int, input().split())
    #A = tuple(map(int, input().split())) #1行ベクトル
    #L = tuple(int(input()) for i in range(N)) #改行ベクトル
    #S = tuple(tuple(map(int, input().split())) for i in range(N)) #改行行列
    a=N//1000
    b=N%1000
    if b==0:
        print(0)
    else:
        print((a+1)*1000-N)





if __name__ == "__main__":
    main()


# Optimized solution
n=eval(input())
n=int(n)
x=n%1000
if x==0:
  print((0))
else:
  print((1000-x))
# Original solution
n=int(eval(input()))
ans=(1000-n%1000)%1000
print(ans)

# Optimized solution
n = int(eval(input()))

print((1000 - n % 1000 if n % 1000 != 0 else 0))
# Original solution
n = int(eval(input()))
if n % 1000 == 0:
    print((0))
else:
    print(((n // 1000 + 1) * 1000 - n))


# Optimized solution
n = int(eval(input()))
print(((1000 - n % 1000) % 1000))
# Original solution
import sys
#input = sys.stdin.buffer.readline


#sys.setrecursionlimit(10**9)
#from functools import lru_cache

def RD(): return sys.stdin.read()
def II(): return int(eval(input()))
def MI(): return list(map(int,input().split()))
def MF(): return list(map(float,input().split()))
def LI(): return list(map(int,input().split()))
def LF(): return list(map(float,input().split()))
def TI(): return tuple(map(int,input().split()))
# rstrip().decode()

#import numpy as np

def main():
	n=II()
	if n%1000==0:
		print((0))
	else:
		print(((n//1000)*1000+1000-n))


if __name__ == "__main__":
	main()


# Optimized solution
n=int(eval(input()))
print(((-n)%1000))
# Original solution
r = 1000 - int(eval(input())) % 1000
print((r if r < 1000 else 0))


# Optimized solution
print(((1000 - int(eval(input())) % 1000) % 1000))
# Original solution
import math

n = int(eval(input()))

print((math.ceil(n/1000)*1000-n))


# Optimized solution
n = int(eval(input()))

p = 0
while p < n:
  p += 1000
print((p - n))
# Original solution
def main():
    N = int(eval(input()))

    change = -N % 1000
    print(change)


if __name__ == '__main__':
    main()


# Optimized solution
def main():
    N = int(eval(input()))

    ans = - N % 1000
    if ans < 0:
        ans += 1000

    print(ans)


if __name__ == '__main__':
    main()
# Original solution
import sys
sys.setrecursionlimit(10 ** 9)
# input = sys.stdin.readline    ####
def int1(x): return int(x) - 1
def II(): return int(eval(input()))
def MI(): return list(map(int, input().split()))
def MI1(): return list(map(int1, input().split()))
def LI(): return list(map(int, input().split()))
def LI1(): return list(map(int1, input().split()))
def LLI(rows_number): return [LI() for _ in range(rows_number)]
def MS(): return input().split()
def LS(): return list(eval(input()))
def LLS(rows_number): return [LS() for _ in range(rows_number)]
def printlist(lst, k=' '): print((k.join(list(map(str, lst)))))
INF = float('inf')
# from math import ceil, floor, log2
# from collections import deque
# from itertools import combinations as comb, combinations_with_replacement as comb_w, accumulate, product, permutations
# from heapq import heapify, heappop, heappush
# import numpy as np    # cumsum
# from bisect import bisect_left, bisect_right

def solve():
    N = II()
    r = N % 1000
    ans = 0
    if r % 1000 != 0:
        ans = 1000 - r
    print(ans)

if __name__ == '__main__':
    solve()


# Optimized solution
import sys
sys.setrecursionlimit(10 ** 9)
# input = sys.stdin.readline    ####
def int1(x): return int(x) - 1
def II(): return int(eval(input()))
def MI(): return list(map(int, input().split()))
def MI1(): return list(map(int1, input().split()))
def LI(): return list(map(int, input().split()))
def LI1(): return list(map(int1, input().split()))
def LLI(rows_number): return [LI() for _ in range(rows_number)]
def MS(): return input().split()
def LS(): return list(eval(input()))
def LLS(rows_number): return [LS() for _ in range(rows_number)]
def printlist(lst, k=' '): print((k.join(list(map(str, lst)))))
INF = float('inf')
# from math import ceil, floor, log2
# from collections import deque
# from itertools import combinations as comb, combinations_with_replacement as comb_w, accumulate, product, permutations
# from heapq import heapify, heappop, heappush
# import numpy as np    # cumsum
# from bisect import bisect_left, bisect_right

def solve():
    N = II()
    r = N % 1000
    if r == 0:
        print((0))
    else:
        print((1000 - r))

if __name__ == '__main__':
    solve()
# Original solution
N = int(eval(input()))
if N%1000 == 0:
    print((0))
else:
    Str = str(N)
    if len(Str) > 3:
        K = (int(Str[0]) + 1) * 1000
        print((K - N))
    else:
        print((1000 - N))


# Optimized solution
n = int(eval(input()))
if n % 1000 == 0:
    print((0))
else:
    k = int(((n/1000)+1))*1000
    print((k-n))
# Original solution
n = int(eval(input()))
if n%1000 == 0:
    print((0))
else:
    k = int((n/1000)+1)*1000
    print((k-n))

# Optimized solution
n = int(eval(input()))
k = int((n/1000)+1)*1000
print((0 if n%1000 == 0 else (k-n)))
# Original solution

n=int(eval(input()))
for i in range(1000,10001,1000):
	num=i-n
	if num >=0:
		print(num)
		break

# Optimized solution
n=int(eval(input()))
for i in range(1000,10001,1000):
	if i>=n:
		print((i-n))
		break
# Original solution
n = int(eval(input()))
print((1000 - n%1000 if n%1000 != 0 else 0))

# Optimized solution
print(((1000-int(eval(input()))%1000)%1000))
# Original solution
n = int(eval(input()))
amari = n%1000
ans = 1000 - amari
if amari == 0:
  print((0))
else:
  print(ans)

# Optimized solution
n = int(eval(input()))
pre = n % 1000
ans = 1000 - pre
if pre == 0:
  print((0))
else:
  print(ans)
# Original solution
from math import ceil

N = int(eval(input()))
print((ceil(N/1000)*1000 - N))

# Optimized solution
N = int(eval(input()))
print(((10000-N)%1000))
# Original solution
import sys, os, math, bisect, itertools, collections, heapq, queue
# from scipy.sparse.csgraph import csgraph_from_dense, floyd_warshall
from decimal import Decimal
from collections import defaultdict, deque

sys.setrecursionlimit(10000000)

ii = lambda: int(sys.stdin.buffer.readline().rstrip())
il = lambda: list(map(int, sys.stdin.buffer.readline().split()))
fl = lambda: list(map(float, sys.stdin.buffer.readline().split()))
iln = lambda n: [int(sys.stdin.buffer.readline().rstrip()) for _ in range(n)]

iss = lambda: sys.stdin.buffer.readline().decode().rstrip()
sl = lambda: list(map(str, sys.stdin.buffer.readline().decode().split()))
isn = lambda n: [sys.stdin.buffer.readline().decode().rstrip() for _ in range(n)]

lcm = lambda x, y: (x * y) // math.gcd(x, y)

MOD = 10 ** 9 + 7
MAX = float('inf')


def main():
    if os.getenv("LOCAL"):
        sys.stdin = open("input.txt", "r")

    N = ii()
    n = 1
    while True:
        if n * 1000 >= N:
            print(((n * 1000) - N))
            exit()
        else:
            n += 1


if __name__ == '__main__':
    main()


# Optimized solution
import sys, os, math, bisect, itertools, collections, heapq, queue
# from scipy.sparse.csgraph import csgraph_from_dense, floyd_warshall
from decimal import Decimal
from collections import defaultdict, deque

sys.setrecursionlimit(10000000)

ii = lambda: int(sys.stdin.buffer.readline().rstrip())
il = lambda: list(map(int, sys.stdin.buffer.readline().split()))
fl = lambda: list(map(float, sys.stdin.buffer.readline().split()))
iln = lambda n: [int(sys.stdin.buffer.readline().rstrip()) for _ in range(n)]

iss = lambda: sys.stdin.buffer.readline().decode().rstrip()
sl = lambda: list(map(str, sys.stdin.buffer.readline().decode().split()))
isn = lambda n: [sys.stdin.buffer.readline().decode().rstrip() for _ in range(n)]

lcm = lambda x, y: (x * y) // math.gcd(x, y)

MOD = 10 ** 9 + 7
MAX = float('inf')


def main():
    if os.getenv("LOCAL"):
        sys.stdin = open("input.txt", "r")

    N = ii()
    print(((1000 - N % 1000) % 1000))


if __name__ == '__main__':
    main()
# Original solution
import math
o = 1000
n = int(eval(input()))
m = math.ceil(n / o) * o - n
print(m)

# Optimized solution
n = int(eval(input()))
t = 1000
while n > t:
    t += 1000
print((t - n))
# Original solution
print(((1000-(int(eval(input()))%1000))%1000))

# Optimized solution
print((-int(eval(input()))%1000))
# Original solution
n = int(eval(input()))
if n % 1000 == 0:
    print((0))
else:
    print((1000 - n % 1000))

# Optimized solution
print(( (1000 - int(eval(input())) % 1000 ) % 1000 ))
# Original solution
import math
N = int(eval(input()))

n = math.ceil(N/1000)
ans = (n*1000) - N

print(ans)


# Optimized solution
import math
N = int(eval(input()))
n = math.ceil(N/1000)*1000

print((n-N))
# Original solution
n=int(eval(input()))
if n<1000:
    print((1000-n))
else:
    str1=""
    k=n//1000
    l=len(str(n))-len(str(k))
    str1=str(k)+'0'*l
    if str1==str(n):
        print((0))
    else:
        p=int(str1)+1000
        print((p-n))

# Optimized solution
n=int(eval(input()))
print(((1000-n%1000)%1000))
# Original solution
# import sys
# import math #sqrt,gcd,pi
# import decimal
# import queue # queue
# import bisect
# import heapq # priolity-queue
# import time
# from itertools import product,permutations,\
#     combinations,combinations_with_replacement
# 重複あり順列、順列、組み合わせ、重複あり組み合わせ
# import collections # deque
# from operator import itemgetter,mul
# from fractions import Fraction
# from functools import reduce

mod = int(1e9+7)
# mod = 998244353
INF = 1<<50

def readInt():
    return list(map(int,input().split()))

def main():
    n = int(eval(input()))
    x = n % 1000
    if x:
        print((1000-x))
    else:
        print((0))
    return

if __name__=='__main__':
    main()


# Optimized solution
n = int(eval(input()))
change = n % 1000
if change:
    print((1000-change))
else:
    print((0))
# Original solution
n=int(eval(input()))
print((1000-n%1000 if n%1000!=0 else 0))

# Optimized solution
n=int(eval(input()))
print((0 if n%1000==0 else 1000-n%1000))
# Original solution
N=int(eval(input()))
if N>1000:
  if N%1000==0:
  	print((0))
  else:
    print((1000-N%1000))
else:
  print((1000-N))

# Optimized solution
N=int(eval(input()))
if N%1000==0:
  print((0))
else:
  print((1000-N%1000))
# Original solution
n = int(eval(input()))
e = 1000
x = n % e
if x == 0:
  print((0))
else:
  print((e-x))

# Optimized solution
n = int(eval(input()))
a = 1000
x = 1
while True:
  if int(a * x) >= n:
    break
  x += 1

print((int(a * x) -n))
# Original solution
n = int(eval(input()))
ans = 0 if n%1000 == 0 else 1000 - n%1000
print(ans)


# Optimized solution
N = int(eval(input()))
print((-N%1000))
# Original solution
N = int(eval(input()))
if N % 1000 == 0:
    print((0))
else:
    n = N // 1000
    print((1000*(n+1)-N))

# Optimized solution
N = int(eval(input()))

print((1000 * ((N - 1) // 1000 + 1) - N))
# Original solution
N = int(eval(input()))
maisuu = int(N/1000)
if N % 1000 == 0:
    money = maisuu*1000
else:
    money = (maisuu+1)*1000

result = money - N
print(result)

# Optimized solution
N = int(eval(input()))
while N > 1000:
    N = N - 1000
print((1000-N))
# Original solution
N = int(eval(input()))

n = -(-N//1000)
print((n*1000 - N))

# Optimized solution
print(((1000 - int(eval(input()))%1000) % 1000))
# Original solution
N = eval(input())
Num = int(N)

while Num > 0:
    OTURI = 1000 - Num
    Num -= 1000
  
print(OTURI)

# Optimized solution
N = int(eval(input()))
OTURI = 0

while N > 0:
    OTURI = 1000 - N
    N -= 1000
  
print(OTURI)
# Original solution
N = int(eval(input()))
s = N // 1000
print((N - 1000 * s if N % 1000 == 0 else (1000 * (s + 1)) - N))

# Optimized solution
print(((1000-int(eval(input()))%1000)%1000))
# Original solution
m=int(eval(input()))
if m%1000==0:
    print((0))
else:
    print((1000-m%1000))

# Optimized solution
m=int(eval(input()))
print(((1000-m%1000)%1000))
# Original solution
ni = lambda: int(eval(input()))
nm = lambda: list(map(int, input().split()))
nl = lambda: list(map(int, input().split()))

import math

n = ni()
if n%1000==0:
  print((0))
else:
  print((1000-n%1000))


# Optimized solution
n=int(eval(input()))
print(((10000-n)%1000))
# Original solution

import heapq
from collections import defaultdict, deque
from math import ceil, factorial, gcd
from itertools import accumulate, permutations

import bisect
# ----------

INF = float("inf")
MOD = 10 ** 9 + 7
# ----------



N = int(eval(input()))

print((ceil(N/1000)*1000-N))


# Optimized solution
N = int(eval(input()))
# 切り上げ
print((-(-N // 1000) * 1000 - N))
# Original solution
import sys
sys.setrecursionlimit(10 ** 5 + 10)
def input(): return sys.stdin.readline().strip()

def resolve():
    
    n=int(eval(input()))
    cnt=0
    while True:
        cnt+=1
        if n<=1000*cnt:
            print((1000*cnt-n))
            break
    
resolve()

# Optimized solution
import sys
sys.setrecursionlimit(10 ** 5 + 10)
def input(): return sys.stdin.readline().strip()

def resolve():
    
    n=int(eval(input()))
    print((0 if n%1000==0 else 1000-(n%1000)))
    
resolve()
# Original solution
import sys
n = int((eval(input())))
if n%1000 == 0:
    print((0))
else:
    while n > 1000:
        n -= 1000
    print((1000-n))

# Optimized solution
import sys
n = int((eval(input())))
if n%1000 == 0:
    print((0))
else:
    for i in range(10):
        if n < 1000:
            print((1000-n))
            sys.exit()
        else:
            n -= 1000
# Original solution
(r, c) = [int(i) for i in input().split()]

ct = [0 for d in range(c)]
tmp = []
for rc in range(r):
    tmp = [int(i) for i in input().split()]
    total = 0
    for cc in range(c):
        ct[cc] += tmp[cc]
        total += tmp[cc]
        print(tmp[cc], end=' ')
    print(total)
total = sum(ct)
print(' '.join([str(i) for i in ct]), total)


# Optimized solution
(r, c) = [int(i) for i in input().split()]

table = []
for rc in range(r):
    table.append([int(i) for i in input().split()])

table.append([0 for _ in range(c + 1)])

for rc in range(r):
    row_total = 0
    for cc in range(c):
        table[r][cc] += table[rc][cc]
        row_total += table[rc][cc]

    table[rc].append(row_total)
    table[r][c] += row_total

for row in table:
    print((' '.join([str(column) for column in row])))
# Original solution
(r, c) = [int(i) for i in input().split()]
 
ct = [0 for d in range(c)]
tmp = []
for rc in range(r):
    tmp = [int(i) for i in input().split()]
    total = 0
    for cc in range(c):
        ct[cc] += tmp[cc]
        total += tmp[cc]
        print(tmp[cc], end=' ')
    print(total)
total = sum(ct)
print(' '.join([str(i) for i in ct]), total)


# Optimized solution
(r, c) = [int(i) for i in input().split()]
last_row = [0 for _ in range(c+1)]

for _ in range(r):
    row = [int(i) for i in input().split()]
    for cc in range(c):
        last_row[cc] += int(row[cc])
        print(row[cc], end=' ')

    print(sum(row))

last_row[-1] = sum(last_row)
print(' '.join([str(a) for a in last_row]))
# Original solution
r, c = list(map(int, input().split(' ')))

matrix = []
total_cols = [0 for i in range(c+1)]

for i in range(r):
    rows  = list(map(int, input().split(' ')));

    total = sum(rows)
    rows.append(total)

    total_cols = [ total_cols[i] + x for i, x in enumerate(rows) ]

    matrix.append(rows)

matrix.append(total_cols)

for row in matrix:
    print((' '.join([str(i) for i in row])))

# Optimized solution
def main():
    r, c = [int(x) for x in input().split()]

    matrix = []
    totals = [0 for _ in range(c+1)]

    for _ in range(r):
        nums = [int(x) for x in input().split()]
        total = sum(nums)

        row = nums + [total]
        matrix.append(row)

        for i in range(c+1):
            totals[i] += row[i]

    matrix.append(totals)

    for m in matrix:
        print((" ".join([str(x) for x in m])))

if __name__ == '__main__':
    main()