Problem:


Score : 500 points

Problem Statement

We have a sequence of N integers: A_1, A_2, \cdots, A_N.

You can perform the following operation between 0 and K times (inclusive):

Choose two integers i and j such that i \neq j, each between 1 and N (inclusive). Add 1 to A_i and -1 to A_j, possibly producing a negative element.

Compute the maximum possible positive integer that divides every element of A after the operations. Here a positive integer x divides an integer y if and only if there exists an integer z such that y = xz.

Constraints

2 \leq N \leq 500

1 \leq A_i \leq 10^6

0 \leq K \leq 10^9

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N K
A_1 A_2 \cdots A_{N-1} A_{N}

Output

Print the maximum possible positive integer that divides every element of A after the operations.

Sample Input 1

2 3
8 20

Sample Output 1

7

7 will divide every element of A if, for example, we perform the following operation:

Choose i = 2, j = 1. A becomes (7, 21).

We cannot reach the situation where 8 or greater integer divides every element of A.

Sample Input 2

2 10
3 5

Sample Output 2

8

Consider performing the following five operations:

Choose i = 2, j = 1. A becomes (2, 6).

Choose i = 2, j = 1. A becomes (1, 7).

Choose i = 2, j = 1. A becomes (0, 8).

Choose i = 2, j = 1. A becomes (-1, 9).

Choose i = 1, j = 2. A becomes (0, 8).

Then, 0 = 8 \times 0 and 8 = 8 \times 1, so 8 divides every element of A. We cannot reach the situation where 9 or greater integer divides every element of A.

Sample Input 3

4 5
10 1 2 22

Sample Output 3

7

Sample Input 4

8 7
1 7 5 6 8 2 6 5

Sample Output 4

5



Sample input:
2 3
8 20


Sample output:
7

Submission status: Accepted

Solution code:
n,k = map(int,input().split())
a = list(map(int,input().split()))
s = sum(a)
div = []
rdiv = []
for i in range(1,int(s**.5+1)):
  if s % i == 0:
    div.append(i)
    rdiv.append(s//i)
if s == int(s**.5)**2:
  div = di[:-1]
rdiv.reverse()
div += rdiv
div.reverse()
#print(div)
for i in range(len(div)):
  now = div[i]
  tmp = []
  for x in a:
    tmp.append(x%now)
  tmp.sort()
  b = n - sum(tmp) // now
  #print(now,tmp,b)
  ans = 0
  for j in range(b):
    ans += tmp[j]
  if ans <= k:
    print(now)
    break

Submission status: Accepted

Solution code:
n, k = list(map(int, input().split()))
nums = list(map(int, input().split()))

def prime_factorize(num):
	x = 1
	fcts = []
	while x * x <= num:
	    if num % x == 0:
	        fcts.append(x)
	        fcts.append(num // x)
	    x += 1
	fcts.sort(reverse = True)
	return fcts

def num_operation(l):
	# lでAの要素を割り切るために必要な操作の回数
	nums_div1 = sorted([x % l for x in nums])
	nums_div2 = [(l - x) % l for x in nums_div1]
	min_op = 10 ** 10

	lf = 0
	rg = sum(nums_div2)
	if rg % l == 0:
		min_op = rg

	for i in range(n):
		lf += nums_div1[i]
		rg -= nums_div2[i]
		if (lf - rg) % l == 0:
			min_op = min(min_op, max(lf, rg))
	return min_op

sum_nums = sum(nums)
fcts = prime_factorize(sum_nums)

for fct in fcts:
	if num_operation(fct) <= k:
		print(fct)
		break

Submission status: Accepted

Solution code:
n, k = map(int, input().split())
arr = list(map(int, input().split()))

# n, k = 8, 7
# arr = list(map(int, "1 7 5 6 8 2 6 5".split()))

add = sum(arr)

def check(factor):
	mod_factor = [x%factor for x in arr]
	mod_factor.sort(reverse = True)
	p = sum(mod_factor)//factor
	# print('p: ', p, 'factor:',factor, 'sum: ', sum(mod_factor))
	# print('mod_factor: ', mod_factor)
	# print(mod_factor[:p])
	c = sum(factor - mod_factor[i] for i in range(p))
	return c <= k

ans = i = 1
while i*i <= add:
	if add % i == 0:
		if check(i):
			ans = max(ans, i)
		if check(add//i):
			ans = max(ans, add//i)
	i += 1
print(ans)

Submission status: Accepted

Solution code:
import sys,collections as cl,bisect as bs
sys.setrecursionlimit(100000)
mod = 10**9+7
Max = sys.maxsize
def l(): #intのlist
    return list(map(int,input().split()))
def m(): #複数文字
    return map(int,input().split())
def onem(): #Nとかの取得
    return int(input())
def s(x): #圧縮
    a = []
    aa = x[0]
    su = 1
    for i in range(len(x)-1):
        if aa != x[i+1]:
            a.append([aa,su])
            aa = x[i+1]
            su = 1
        else:
            su += 1
    a.append([aa,su])
    return a
def jo(x): #listをスペースごとに分ける
    return " ".join(map(str,x))
def max2(x): #他のときもどうように作成可能
    return max(map(max,x))
def prime_decomposition(n): #素因数分解
  i = 2
  table = []
  while i * i <= n:
    while n % i == 0:
      n /= i
      table.append(i)
    i += 1
  if n > 1:
    table.append(int(n))
  return table

def make_divisors(n): #約数列挙
    divisors = []
    for i in range(1, int(n**0.5)+1):
        if n % i == 0:
            divisors.append(i)
            if i != n // i:
                divisors.append(n//i)

    divisors.sort()
    return divisors



n,k = m()

a = l()

p = sum(a)

d = make_divisors(p)

ans = 0

for i in d:
    kkk = [0] * n
    for j in range(n):
        kkk[j] = a[j] % i
    kkk.sort()
    kkkk = sum(kkk)
    nw = 0
    for j in range(n):
        nw += kkk[j]
        nn = kkkk - nw
        if nw <= k and (n-j-1)*i - nn <= k and nw == (n-j-1)*i - nn:
            ans = i
            break
print(ans)

Submission status: Accepted

Solution code:
n, k = map(int,input().split())
a = list(map(int,input().split()))


def d(x):
    l = []
    for i in range(1, int(x**0.5)+1):
        if x%i==0:
            l.append(i)
            if i != x//i:
                l.append(x//i)
    l.sort(reverse=True)
    return l

s = d(sum(a))
for i in s:
    x = [0 for k in range(n)]
    for j in range(len(a)):
        x[j] = a[j] % i
    x.sort()
    l = [0 for k in range(n+1)]
    r = [0 for k in range(n+1)]
    for j in range(n+1):
        if j == 0:
            l[0] = 0
            r[n-0] = 0
        else:
            l[j] = l[j-1] + x[j-1]
            r[n-j] = r[n-j+1] + (i-x[n-j])
    ans = 1
    for j in range(n+1):
        if l[j] == r[j] and l[j] <= k:
            ans = i
            print(ans)
            exit()

Submission status: Accepted

Solution code:
# -*- coding: utf-8 -*-
"""
Created on Mon Aug 19 22:50:08 2019

@author: Yamazaki Kenichi
"""
import functools

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

S = sum(A)

def make_divisors(n):
    divisors = []
    for i in range(1,int(n**0.5)+1):
        if n % i == 0:
            divisors.append(i)
            if i != n // i:
                divisors.append(n//i)
    return divisors
def dfs(x,d):
    return x%d

D = make_divisors(S)
ans = 1
for d in D:
    B = list(map(functools.partial(dfs,d=d),A[:]))
    B.sort()
    l, r, tmp = 0, N-1, 0
    res = 0
    while l <= r:
        if B[l] + B[r] + tmp == d:
            res += B[l]
            tmp = 0
            l += 1
            r -= 1
        elif B[l] + B[r] + tmp < d:
            tmp = B[l] + tmp
            res += B[l]
            l += 1
        else:
            tmp = B[r] + tmp - d 
#            res += B[l]
            r -= 1
#        print(l,r,tmp,res)
    if res <= K and d > ans:
        ans = d
print(ans)

Submission status: Accepted

Solution code:
# E - Max GCD ★

def slvDivisor(summary):
    divisor = set()
    for d in range(1, int(summary ** 0.5) + 1):
        if summary % d == 0:
            divisor.add(d)
            divisor.add(summary // d)
    return divisor



input1 = list(map(int, input().split()))
n = input1[0]
k = input1[1]
a = list(map(int, input().split()))

# 和の約数を求める
sumA = sum(a)
divisor = slvDivisor(sumA)

# 各値を約数で割った際の余りも約数の整数倍（i倍とする）になるはず
# → ＋－する操作はその余りを他の値に移動して約数を作る操作になる
# → 余りが小さい値から大きい値へ余りを寄せていくのが効率的
# → 寄せきると約数 * i個、0 * (N - i)個の2ブロックに分かれる
# → 寄せきるまでの回数がk以下ならOK
for d in sorted(divisor, reverse=True):
    modA = [x % d for x in a]
    modA.sort()
    i = sum(modA) // d
    cnt = sum(modA[:-i])
    if cnt <= k:
        print(d)
        break

Submission status: Accepted

Solution code:
N , K = map(int, input().split())
A = list(map(int, input().split()))
s = sum(A)
divisor = []
n = 1
while n ** 2 <= s:
    q, r = divmod(s, n)
    if r == 0:
        divisor.append(q)
        divisor.append(n)
    n += 1
if n ** 2 == s:
    divisor.pop()
ans = 1
for d in divisor:
    m = []
    for a in A:
        m.append(a % d)
    m.sort(reverse=True)
    l = sum(m) // d
    a = l * d - sum(m[:l])
    if a <= K:
        ans = max(ans, d)
print(ans)

Submission status: Accepted

Solution code:
inputs = [int(x) for x in input().split()]
n, k = inputs[0], inputs[1]
ls = [int(x) for x in input().split()]
s = sum(ls)

# https://qiita.com/LorseKudos/items/9eb560494862c8b4eb56
divisors = []
for i in range(1, int(s ** 0.5) + 1):
  if s % i == 0:
    divisors.append(i)
    if i != s // i:
      divisors.append(s // i)

divisors.sort(reverse=True)
ans = 1
for d in divisors:
  mods = sorted([l % d for l in ls if l % d != 0])
  opcnt = 0
  is_success = False
  # print("{}: {}".format(d, ", ".join([str(m) for m in mods])))
  while True:
    if opcnt > k or len(mods) == 1:
      # print("opcnt: {}".format(opcnt))
      is_success = False
      break

    if len(mods) == 0:
      is_success = True
      ans = d
      # print("ans: {}, opcnt: {}".format(ans, opcnt))
      break

    if mods[0] + mods[-1] < d:
      mods[-1] += mods[0]
      opcnt += mods[0]
      mods.pop(0)
    elif mods[0] + mods[-1] == d:
      opcnt += mods[0]
      mods.pop(0)
      mods.pop(-1)
    else:
      opcnt += (d - mods[-1])
      mods[0] -= (d - mods[-1])
      mods.pop(-1)
    # print("{}: {}".format(d, ", ".join([str(m) for m in mods])))


  if is_success:
    break

print(ans)

Submission status: Accepted

Solution code:
N, K = map(int, input().split())
a_list = list(map(int, input().split()))
 
total_a = sum(a_list)
#約数の列挙
candidates = set()
for i in range(1, total_a):
    if i * i > total_a:
        break
    if total_a % i == 0:
        candidates.add(i)
        candidates.add(total_a // i)        
ans = 1
for x in candidates:
    remainders = sorted(map(lambda a: a % x, a_list))
    total_r = sum(remainders)    
    border = total_r // x
    need = sum(remainders[:(N - border)])
    
    # print(x, remainders, total_r, border, need)
    if need <= K:
        ans = max(ans, x)
print(ans)

Submission status: Accepted

Solution code:
n, k  = map(int, input().split())
l = list(map(int, input().split()))
s = sum(l)
#print(l)

def make_divisors(n):
  divisors = []
  for i in range(1, int(n**0.5)+1):
    if n % i == 0:
      divisors.append(i)
      if i != n // i:
        divisors.append(n//i)
  divisors.sort()
  return divisors

d = make_divisors(s)
#print(d)

ans = 0
for i in d:
  m = [0]*n
  for j in range(n):
    m[j] = l[j]%i
  m.sort()
  #print(m)
  sm = sum(m)
  sl = 0
  for p in range(n):
    sl += m[p]
    sr  = sm-sl
    if sl <= k and (n-p-1)*i-sr <= k and sl == (n-p-1)*i-sr:
      ans = i
      break
print(ans)

Submission status: Accepted

Solution code:
#
def div(n): #約数を求める
 ret=[]
 for i in range(1,int(n**0.5)+1):
   if n%i==0:
     ret.append(i)
     if i!=n//i:
       ret.append(n//i)
 return ret

n,k=map(int,input().split())
arr=list(map(int,input().split()))
ans=1
d=div(sum(arr))
for val in d: #すべての約数について条件判定
 arr=sorted(arr,key=lambda x:x%val) #配列を、約数で割ったあまりが小さい順にソート
 parr=[] #配列の各要素を(x-arr[i]%x)足すときの操作回数
 narr=[] #配列の各要素をarr[i]%x引くときの操作回数
 for num in arr:
   narr.append(num%val)
   parr.append(val-num%val)
 for i in range(n-1): #上記の値の累積和を取る
   parr[i+1]+=parr[i]
   narr[i+1]+=narr[i]
 for i in range(n-1): #累積和を用いて条件判定
   ncnt=narr[i] #左からi番目の要素まで、各要素が約数の倍数になるように値を引くときの操作回数
   pcnt=parr[-1]-parr[i] #左からi+1番目の要素から右端の要素まで、各要素が約数の倍数になるように値を足すときの操作回数
   if ncnt!=pcnt: #足す回数と引く回数が一致していなければそもそも操作は不可能
     continue
   else:
     if pcnt<=k: #操作回数がK以下であればその約数は答えの候補になる
       ans=max(ans,val)
print(ans) #答えの候補となる約数の最大値が答えとなる

Submission status: Accepted

Solution code:
# cook your dish here

n, k = map(int,input().split())
a = list(map(int,input().split()))

Sum = sum(a)

divisor = []
i = 1
while i*i <= Sum:
    if Sum % i == 0:
        divisor.append(i)
        divisor.append(Sum//i)
    i += 1
    
divisor = set(divisor)

ans = 0
for div in divisor:
    remain = []
    for ai in a:
        remain.append(ai % div)
    
    remain.sort()
    l = 0 
    r = len(remain) - 1;
    
    operator = 0
    while l < r:
        need = min(remain[l],div - remain[r])
        operator += need
        
        remain[l] -= need
        remain[r] += need
        
        if remain[l] == 0: l += 1
        if remain[r] == div: r -= 1
    
    if (operator <= k): ans = max(ans, div)    


print(ans)

Submission status: Accepted

Solution code:
import sys
input = sys.stdin.readline

N, M = map(int, input().split())
L = [int(v) for v in input().split()]
L.sort()

s = sum(L)
d = set()
for i in range(1, int(s ** 0.5) + 1):
    if s % i == 0:
        d.add(i)
        d.add(s // i)
        
d = list(d)
d.sort(reverse = True)

ans = 1
for n in d:
    p = [v % n for v in L]
    p.sort()
    pc = n * N - sum(p)
    mc = 0
    for v in p:
        pc -= (n - v)
        mc += v
        
        if pc == mc:
            break
                
    if pc <= M:
        ans = max(ans, n)

print(ans)

Submission status: Accepted

Solution code:
from itertools import accumulate
N, K = map(int, input().split())
A = list(map(int, input().split()))

S = sum(A)
ans_candidate = []
for i in range(1, int(S ** 0.5) + 1):
    if S % i == 0:
        ans_candidate.append(i)
        ans_candidate.append(S // i)


ans = 1
for z in ans_candidate:
    modZ_down = sorted([a % z for a in A])
    modZ_up = sorted([z - mzd for mzd in modZ_down], reverse=True)

    modZ_down = list(accumulate(modZ_down))
    modZ_up = list(accumulate(modZ_up[::-1]))[::-1]

    for i in range(N - 1):
        if (modZ_down[i] == modZ_up[i + 1]) and (modZ_down[i] <= K):
            ans = max(ans, z)

print(ans)

Submission status: Accepted

Solution code:
N, K = map(int, input().split())
A = list(map(int, input().split()))

# nの約数を求める。計算量O(sqrt(N))
def get_divisors(n, reverse=False):
    from math import sqrt
    divisors = []
    for num in range(1, int(sqrt(n))+1):
        if n % num == 0:
            divisors.append(num)
            if n//num != num:
                divisors.append(n//num)
    return sorted(divisors, reverse=reverse)

total = sum(A)
divisors = get_divisors(total, reverse=True)
ans = -1
for d in divisors:
    R = [a%d for a in A]
    R.sort(reverse=True)
    pr = 0
    nr = -sum(R)
    for i, r in enumerate(R):
        pr += d-r
        nr += r
        if nr+pr >= 0:
            if pr <= K and nr+pr == 0:
                ans = d
            break
    if ans != -1:
        print(ans)
        break
else:
    print(1)

Submission status: Accepted

Solution code:
N, K = map(int, input().split())
A = list(map(int, input().split()))

# nの約数を求める。計算量O(sqrt(N))
def get_divisors(n):
    from math import sqrt, ceil
    from collections import deque
    divisors = deque([])
    for num in range(ceil(sqrt(n)), n+1):
        if n % num == 0:
            divisors.append(n//num)
            if n//num != n:
                divisors.appendleft(num)
    return list(divisors)


def make_divisors(n):
    divisors = []
    for i in range(1, int(n**0.5)+1):
        if n % i == 0:
            divisors.append(i)
            if i != n//i:
                divisors.append(n//i)
    divisors.sort(reverse=True)
    return divisors

total = sum(A)
divisors = make_divisors(total)
ans = -1
for d in divisors:
    R = [a%d for a in A]
    R.sort(reverse=True)
    pr = 0
    nr = -sum(R)
    for i, r in enumerate(R):
        pr += d-r
        nr += r
        if nr+pr >= 0:
            if pr <= K and nr+pr == 0:
                ans = d
            break
    if ans != -1:
        print(ans)
        break
else:
    print(1)

Submission status: Accepted

Solution code:
from math import sqrt, floor
from itertools import accumulate

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

def divisors(n):
    ds = [d for d in range(1, floor(sqrt(n)) + 1) if n % d == 0]
    for d in ds:
        yield n // d
    if n == ds[-1] ** 2:
        ds.pop(-1)
    ds.reverse()
    for d in ds:
        yield d

S = sum(A)
for d in divisors(S):
    X = [a % d for a in A]
    X.sort()
    AC = accumulate(X)
    SB = accumulate(reversed([(d - x) % d for x in X]))
    SB = reversed(list(SB)[:-1])
    k = [a for a, s in zip(AC, SB) if a == s][0]
    if k <= K:
        print(d)
        break

Submission status: Accepted

Solution code:
def make_divisors(n):
    divisors=[]
    for i in range(1,int(n**0.5)+1):
        if n%i==0:
            divisors.append(i)
            if i!=n//i:
                divisors.append(n//i)
    divisors.sort()
    return divisors
def judge(d):
    R=[]
    for a in A:
        R.append(a%d)
    R.sort()
    R_rev=[]
    for r in R:
        R_rev.append(d-r)
    R_acc=[0]*(n+1); R_rev_acc=[0]*(n+1)
    for i in range(n):
        R_acc[i+1]=R_acc[i]+R[i]
    for i in reversed(range(n)):
        R_rev_acc[i]=R_rev_acc[i+1]+R_rev[i]
    tmp=float('inf')
    for i in range(n+1):
        tmp=min(tmp,max(R_acc[i],R_rev_acc[i]))
    return tmp<=k

n,k=map(int,input().split())
A=tuple(map(int,input().split()))
s=sum(A)
D=make_divisors(s)
ans=1
for d in D:
    if judge(d):
        ans=d
print(ans)

Submission status: Accepted

Solution code:
N, K = map(int, input().split())
a_list = list(map(int, input().split()))

total_a = sum(a_list)
#約数の列挙
candidates = set()
for i in range(1, total_a):
    if i * i > total_a:
        break
    if total_a % i == 0:
        candidates.add(i)
        candidates.add(total_a // i)

ans = 1
for x in candidates:
    remainders = sorted(map(lambda a: a % x, a_list))
    total_r = sum(remainders)
    border = total_r // x
    need = sum(remainders[:(N - border)])
    if need <= K:
        ans = max(ans, x)
print(ans)

Submission status: Accepted

Solution code:
n,limit = map(int,input().split())
a = list(map(int, input().split()))

su = 0
for i in range(n):
    su += a[i]

factors = set()

for i in range(1,int(su**0.5)+1):
    if su%i == 0:
        factors.add(i)
        factors.add(int(su/i))

factors = list(factors)
factors = sorted(factors)

def check(k):
    #print(str(k)+"をチェックします")
    n_sum = 0
    p_sum = 0
    nas = []
    pas = []
    for i in range(n):
        na = a[i]%k
        pa = k-na
        n_sum += na
        p_sum += pa
        nas.append(na)
        pas.append(pa)
    if n_sum%k != 0:
        return 0
    nas = sorted(nas)
    pas = sorted(pas)
    #print(nas)
    #print(pas)
    
    s_nas = []
    s_pas = []
    su_nas = 0
    su_pas = 0
    for i in range(n):
        su_nas += nas[i]
        su_pas += pas[i]
        s_nas.append(su_nas)
        s_pas.append(su_pas)
    #print(s_nas)
    #print(s_pas)
        
    for i in range(n):
        if s_nas[i] == s_pas[n-i-2] and s_nas[i] <= limit:
            #print(s_nas[i],s_pas[n-i-2])
            return 1
    return 0


ma = 1
#print(factors)

for i in range(len(factors)):
    if (check(factors[i])):
        ma = factors[i]

print(ma)

Submission status: Accepted

Solution code:
def make_divisors(n):
    divisors = []
    for i in range(1, int(n**0.5)+1):
        if n % i == 0:
            divisors.append(i)
            if i != n // i:
                divisors.append(n//i)

    divisors.sort(reverse = True)
    return divisors
N, K = map(int, input().split())
A = list(map(int, input().split()))
m = sum(A)
divisors = make_divisors(m)
for d in divisors:
    A1 = list(map(lambda x:x%d, A))
    A1.sort()
    res = 0
    index = N
    for i in range(N):
        res+=A1[i]
        if res>K:
            res-=A1[i]
            index = i
            break
    
    res1 = 0
    for i in range(index, N):
        res1+=d-A1[i]
    if res>=res1:
        ans = d
        break
print(ans)

Submission status: Accepted

Solution code:
def main(sample_file = ''):

    """ convenient functions
    # for i, a in enumerate(iterable)
    # q, mod = divmod(a, b)
    # divmod(x, y) returns the tuple (x//y, x%y)
    # Higher-order function: reduce(operator.mul, xyz_count, 1)
    # manage median(s) using two heapq https://atcoder.jp/contests/abc127/tasks/abc127_f
    """

    """convenient decorator
    # @functools.lru_cache():
    # to facilitate use of recursive function
        # ex:
        # from functools import lru_cache
        # import sys
        # sys.setrecursionlimit(10**9)
        # @lru_cache(maxsize=None)
        # def fib(n):
        #     if n < 2:
        #         return n
        #     return fib(n-1) + fib(n-2)
        # print(fib(1000))
    """
    
    # import numpy as np
    import sys
    sys.setrecursionlimit(10**7)
    from itertools import accumulate, combinations, permutations, product # https://docs.python.org/ja/3/library/itertools.html
    # accumulate() returns iterator! to get list: list(accumulate())
    from math import factorial, ceil, floor, sqrt
    def factorize(n):
        """return the factors of the Arg and count of each factor
        
        Args:
            n (long): number to be resolved into factors
        
        Returns:
            list of tuples: factorize(220) returns [(2, 2), (5, 1), (11, 1)]
        """
        fct = []  # prime factor
        b, e = 2, 0  # base, exponent
        while b * b <= n:
            while n % b == 0:
                n = n // b
                e = e + 1
            if e > 0:
                fct.append((b, e))
            b, e = b + 1, 0
        if n > 1:
            fct.append((n, 1))
        return fct
    def combinations_count(n, r):
        """Return the number of selecting r pieces of items from n kinds of items.
        
        Args:
            n (long): number
            r (long): number
        
        Raises:
            Exception: not defined when n or r is negative
        
        Returns:
            long: number
        """
        # TODO: How should I do when n - r is negative?
        if n < 0 or r < 0:
            raise Exception('combinations_count(n, r) not defined when n or r is negative')
        if n - r < r: r = n - r
        if r < 0: return 0
        if r == 0: return 1
        if r == 1: return n
        numerator = [n - r + k + 1 for k in range(r)]
        denominator = [k + 1 for k in range(r)]
        for p in range(2,r+1):
            pivot = denominator[p - 1]
            if pivot > 1:
                offset = (n - r) % p
                for k in range(p-1,r,p):
                    numerator[k - offset] /= pivot
                    denominator[k] /= pivot
        result = 1
        for k in range(r):
            if numerator[k] > 1:
                result *= int(numerator[k])
        return result
    def combinations_with_replacement_count(n, r):
        """Return the number of selecting r pieces of items from n kinds of items allowing individual elements to be repeated more than once.
        
        Args:
            n (long): number
            r (long): number
        
        Raises:
            Exception: not defined when n or r is negative
        
        Returns:
            long: number
        """
        if n < 0 or r < 0:
            raise Exception('combinations_with_replacement_count(n, r) not defined when n or r is negative')
        elif n == 0:
            return 1
        else:
            return combinations_count(n + r - 1, r)
    from bisect import bisect_left, bisect_right
    from collections import deque, Counter, defaultdict # https://docs.python.org/ja/3/library/collections.html#collections.deque
    from heapq import heapify, heappop, heappush, heappushpop, heapreplace,nlargest,nsmallest # https://docs.python.org/ja/3/library/heapq.html
    from copy import deepcopy, copy # https://docs.python.org/ja/3/library/copy.html
    import operator
    from operator import itemgetter #sort 
    # ex1: List.sort(key=itemgetter(1))
    # ex2: sorted(tuples, key=itemgetter(1,2))
    from functools import reduce, lru_cache
    def chmin(x, y):
        """change minimum
        if x > y, x = y and return (x, True).
        convenient when solving problems of dp[i]
        
        Args:
            x (long): current minimum value
            y (long): potential minimum value
        
        Returns:
            (x, bool): (x, True) when updated, else (x, False)
        """
        if x > y:
            x = y
            return (x, True)
        else:
            return (x, False)
    def chmax(x, y):
        """change maximum
        if x < y, x = y and return (x, True).
        convenient when solving problems of dp[i]
        
        Args:
            x (long): current maximum value
            y (long): potential maximum value
        
        Returns:
            (x, bool): (x, True) when updated, else (x, False)
        """
        if x < y:
            x = y
            return (x, True)
        else:
            return (x, False)

    from fractions import gcd # Deprecated since version 3.5: Use math.gcd() instead.
    def gcds(numbers):
        return reduce(gcd, numbers)
    def lcm(x, y):
        return (x * y) // gcd(x, y)
    def lcms(numbers):
        return reduce(lcm, numbers, 1)
    def make_divisors(n, reversed=False):
        """create list of divisors
        
        Args:
            number (int): number from which list of divisors is created
            reversed (bool, optional): ascending order if False. Defaults to False.
        
        Returns:
            list: list of divisors
        """
        divisors = set()
        for i in range(1, int(n**0.5)+1):
            if n % i == 0:
                divisors.add(i)
                divisors.add(n//i)
        return sorted(list(divisors),reverse=reversed)
    
    # first create factorial_list
    # fac_list = mod_factorial_list(n)
    INF = 10 ** 18
    MOD = 10 ** 9 + 7
    modpow = lambda a, n, p = MOD: pow(a, n, p) # Recursive function in python is slow!
    def modinv(a, p = MOD):
        # evaluate reciprocal using Fermat's little theorem:
        # a**(p-1) is identical to 1 (mod p) when a and p is coprime
        return modpow(a, p-2, p)
    def modinv_list(n, p = MOD):
        if n <= 1:
            return [0,1][:n+1]
        else:
            inv_t = [0,1]
            for i in range(2, n+1):
                inv_t += [inv_t[p % i] * (p - int(p / i)) % p]
            return inv_t
    def modfactorial_list(n, p = MOD):
        if n == 0:
            return [1]
        else:
            l = [0] * (n+1)
            tmp = 1
            for i in range(1, n+1):
                tmp = tmp * i % p
                l[i] = tmp
            return l
    def modcomb(n, k, fac_list = [], p = MOD):
        # fac_list = modfactorial_list(100)
        # print(modcomb(100, 5, modfactorial_list(100)))
        from math import factorial
        if n < 0 or k < 0 or n < k: return 0
        if n == 0 or k == 0: return 1
        if len(fac_list) <= n:
            a = factorial(n) % p
            b = factorial(k) % p
            c = factorial(n-k) % p
        else:
            a = fac_list[n]
            b = fac_list[k]
            c = fac_list[n-k]
        return (a * modpow(b, p-2, p) * modpow(c, p-2, p)) % p
    def modadd(a, b, p = MOD):
        return (a + b) % MOD
    def modsub(a, b, p = MOD):
        return (a - b) % p
    def modmul(a, b, p = MOD):
        return ((a % p) * (b % p)) % p
    def moddiv(a, b, p = MOD):
        return modmul(a, modpow(b, p-2, p))

    class UnionFindTree:
        """union find tree class
        TODO: fix this description...
        how to use (example):
        >>  uf = UnionFindTree(N) 
        >>  if uf.find_root(a) == uf.find_root(b):
        >>      do something
        >>  else:
        >>      do something
        >>      uf.unite(a, b)
        """
        def __init__(self, N):
            self.root = [-1] * (N+1)
            self.rank   = [0]  * (N+1)
            self.connected_num = [1] * (N+1)
    
        def find_root(self,x):
            root = self.root
            while root[x] != -1:
                x = root[x]
            return x
    
        def unite(self,x,y):
            root = self.root
            rank = self.rank
            connected_num = self.connected_num
            find_root = self.find_root
    
            rx = find_root(x)
            ry = find_root(y)
            if rx != ry:
                if rank[rx] < rank[ry]:
                    root[rx] = ry
                    rx,ry = ry,rx
                else:
                    if rank[rx] == rank[ry]:
                        rank[rx] += 1
                    root[ry] = rx       
                connected_num[rx] += connected_num[ry]

    """ initialize variables and set inputs
    # initialize variables
        # to initialize list, use [0] * n
        # to initialize two dimentional array, use [[0] * N for _ in range(N)]
    # set inputs
        # put inputs between specific values (almost as quickly)
        # ex) S = [-INF] + [int(r()) for _ in range(A)] + [INF]
        # open(0).read() is sometimes useful:
        # ex) n, m, *x = map(int, open(0).read().split())
        #     min(x[::2]) - max(x[1::2])
        # ex2) *x, = map(int, open(0).read().split())
        #     don't forget to add comma after *x if only one variable is used
    # preprocessing
        # transpose = [x for x in zip(*data)]
        # ex) [[1, 2, 3], [4, 5, 6], [7, 8, 9]] => [(1, 4, 7), (2, 5, 8), (3, 6, 9)]
        # flat = [flatten for inner in data for flatten in inner]
        # ex) [[1, 2, 3], [4, 5, 6], [7, 8, 9]] => [1, 2, 3, 4, 5, 6, 7, 8, 9]
    # calculate and output
        # output pattern
        # ex1) print(*l) => when l = [2, 5, 6], printed 2 5 6
    """

    # functions used
    r = lambda: sys.stdin.readline().strip()
    r_int = lambda: int(r())
    R = lambda: list(map(int, r().split()))
    Rmap = lambda: map(int, r().split())
    Rfloat = lambda: list(map(float, r().split()))
    Rtuple = lambda: tuple(map(int, r().split()))

    """ how to treat input
    # single int: int(r())
    # single string: r()
    # single float: float(r())
    # line int: R()
    # line string: r().split()
    # line (str, int, int): [j if i == 0 else int(j) for i, j in enumerate(r().split())]
    # lines int: [R() for _ in range(n)]
    """

    # for test
    if sample_file:
        sys.stdin = open(sample_file)
        
    # ----------------------------------
    # main

    N, K = R()
    A = R()
    A.sort(reverse=True)
    Remain = [0] * N
    sumA = sum(A)

    divisors = make_divisors(sumA, True)
    for divisor in divisors:
        for i in range(N):
            Remain[i] = A[i] % divisor
        Remain.sort()
        RemainSum = sum(Remain)
        split = RemainSum//divisor
        cnt = sum(Remain[:-split])
        if cnt <= K:
            print(divisor)
            return
        
    # end of main
    # ----------------------------------

    """memo: how to use defaultdict of list
    # initialize
    Dic = defaultdict(list)
    # append / extend
    Dic[x].append(y)
    # three methods for loop: keys(), values(), items()
    for k, v in Dic.items():
    """
    
    """memo: how to solve binary problems
    # to make binary digits text
    >>> a = 5
    >>> bin_str_a = format(a, '#06b')
    >>> print(bin_str_a)
    0b0101 # first 2 strings (='0b') indicates it is binary
    """
    
    """memo: how to solve the problem
    creating simple test/answer
    greed
    simple dp
    graph
    """

if __name__ == '__main__':
    main()