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

Solution (Python):
import math
import os
import sys

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

sys.setrecursionlimit(2147483647)
INF = float("inf")
IINF = 10 ** 18
MOD = 10 ** 9 + 7


def get_divisors(n):
    """
    n の約数をリストで返す
    :param int n:
    :rtype: list of int
    """
    ret = []
    for i in range(1, int(math.sqrt(n)) + 1):
        if n % i == 0:
            ret.append(i)
            if n // i != i:
                ret.append(n // i)
    return ret


def can_make(div):
    mods = []
    for a in A:
        mods.append(a % div)

    mods.sort()
    left = 0
    right = len(mods) - 1
    k = K
    while left <= right and k >= 0:
        while left < len(mods) and mods[left] % div == 0:
            left += 1
        while right >= 0 and mods[right] % div == 0:
            right -= 1
        if right < left:
            return True

        m = div - mods[right]
        if mods[left] >= m:
            mods[left] -= m
            mods[right] = 0
            right -= 1
            k -= m
        else:
            mods[right] += mods[left]
            k -= mods[left]
            mods[left] = 0
            left += 1
    return k >= 0


N, K = list(map(int, sys.stdin.readline().split()))
A = list(map(int, sys.stdin.readline().split()))


divs = get_divisors(sum(A))
for div in sorted(divs, reverse=True):
    if can_make(div):
        print(div)
        exit()
assert False

Solution (Python):
def all_divisor(n):
    small = [1]
    large = [n]
    for i in range(2, int(n ** 0.5) + 1):
        if not (n % i):
            small.append(i)
            large.append(n//i)
    large.reverse()
    divisor = small + large
    return divisor

n, k = map(int, input().split())
a = list(map(int, input().split()))
sum_a = sum(a)
divisor = all_divisor(sum_a)
ans = 1
for i in reversed(divisor):
  t = 0
  b = []
  d = 0
  for j in a:
    b.append(j % i)
  c = sum(b)
  b.sort()
  for x in reversed(b):
    c -= x
    d += i - x
    if c == d:
      if c <= k:
        print(i)
        exit()
print(ans)

Solution (Python):
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 = map(int,input().split())
A = list(map(int,input().split()))
D = sum(A)
D = make_divisors(D)[::-1]

for d in D:
    a = []
    for i in range(N):
        if A[i]%d != 0:
            a.append(A[i]%d)
    a.sort()
    b = [d-x for x in a]
    b.sort()

    c1 = [0]*(len(a)+1)
    for i in range(len(a)):
        c1[i] = a[i]+c1[i-1]
    c2 = [0]*(len(b)+1)
    for i in range(len(b)):
        c2[i] = b[i]+c2[i-1]

    k = float('inf')
    for i in range(len(a)):
        if c1[i] == c2[len(a)-2-i]:
            k = c1[i]
            break
    if k <= K:
        break
print(d)

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

nums = A[:]

sum_n = sum(nums)

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

divisors = sorted(list(make_divisors(sum_n)), reverse=True)



for d in divisors:
    mod_nums = list(map(lambda x: x%d, nums[:]))
    mod_nums = sorted(mod_nums)
    
    x = 10**10
    for i in range(0, len(mod_nums)+1):
        if sum(mod_nums[:i]) == sum(list(map(lambda x: d-x, mod_nums[i:]))):
            x = sum(mod_nums[:i])
            break
    
    if x <= K:
        ans = d
        break
            
print(ans)

Solution (Python):
import sys
from collections import deque, defaultdict
import copy
import bisect
input=sys.stdin.readline

import math
import heapq

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

sumA = sum(A)
yakusu = []
yakusu2 = []
t = 1
while t <= sumA ** 0.5:
	if sumA % t == 0:
		yakusu.append(t)
		yakusu2.append(sumA // t)
	t+=1
while len(yakusu) > 0:
	yakusu2.append(yakusu.pop())


for num in yakusu2:
	sa = []
	for i in range(N):
		syo = A[i]//num
		sa.append(A[i]-num*syo)
	sa.sort()
	judge = 0
	wa = 0
	loc = 0
	for i in range(len(sa)):
		
		if (wa + sa[i]) <= K:
			wa += sa[i]
			loc = i
		else:
			break
	if loc == len(sa) - 1:
		print(num)
		exit()
	else:
		for i in range(loc+1, len(sa)):
			sa[i] = num - sa[i]
	
	if sum(sa[loc+1:]) <= K:
		print(num)
		exit()

Solution (Python):
from math import sqrt
n, k = map(int, input().split())
a = list(map(int, input().split()))
s = sum(a)
div = []
for i in range(1, int(sqrt(s)+1)):
	if s%i == 0:
		if i*i != s:
			div.append(s//i)
		div.append(i)
div.sort(reverse=True)


for d in div:
	b = [x%d for x in a if x%d != 0]
	if not b:
		print(d)
		break
	b.sort(key=lambda x: x%d)
	y, z = 0, d*len(b)-sum(b)
	res = 10**30
	for x in b:
		y += x
		z -= d-x
		res = min(res, max(y, z))
	if res <= k:
		print(d)
		break

Solution (Python):
from math import sqrt
class Factorizer:
    def __init__(self):
        self.primes_ceil = 5
        self.primes = [2,3]

    def find_primes(self, primes_ceil):
        if primes_ceil <= self.primes_ceil:
            return self.primes

        prev_primes_ceil, self.primes_ceil = self.primes_ceil, primes_ceil
        r, m = prev_primes_ceil//6, prev_primes_ceil%6
        if m <= 1:
            i = r*6 + 1
            mod_flag = True
        else:
            i = r*6 + 5
            mod_flag = False

        while i < self.primes_ceil:
            sieve = True
            for p in self.primes:
                if p*p > i:
                    break
                elif i % p == 0:
                    sieve = False
                    break
            if sieve:
                self.primes.append(i)
            if mod_flag:
                i += 4
                mod_flag = False
            else:
                i += 2
                mod_flag = True

        return self.primes

    def __call__(self, n):
        if (self.primes_ceil-1)**2 < n:
            self.find_primes(int(sqrt(n))+1)
        factors = []
        powers = []
        for p in self.primes:
            if p * p > n:
                break
            elif n % p == 0:
                n //= p
                k = 1
                while n % p == 0:
                    n //= p
                    k += 1
                factors.append(p)
                powers.append(k)
        if n > 1:
            factors.append(n)
            powers.append(1)
        return factors, powers

inpl = lambda: list(map(int,input().split()))
N, K = inpl()
A = inpl()
S = sum(A)
factorize = Factorizer()

ft, pw = factorize(S)
n = len(ft)
denominators = [1]
for i in range(n):
    new_denominators = []
    for d in denominators:
        for p in range(pw[i]+1):
            new_denominators.append(d*(ft[i]**p))
    denominators = new_denominators
denominators.sort(reverse=True)

for d in denominators:
    mods = [a%d for a in A]
    mods.sort()
    Sm = sum(mods)
    h = Sm // d
    minK = min(d*(h+1)-sum(mods[N-h-1:]), sum(mods[:N-h]))
    if minK <= K:
        print(d)
        exit()

Solution (Python):
from collections import defaultdict, deque
import sys
import math

sys.setrecursionlimit(100000)

MIN = -10 ** 9
MAX = 10 ** 9 + 7


def main():
    
    N, K = [int(a) for a in input().split()]
    
    
    
    
    A = sorted([int(a) for a in input().split()])
    SUM = sum(A)

    
    
    
    
    
    
    
    
    
    
    
    
    
    

    def check(nn):
        r = []
        for a in A:
            amari = a % nn
            if amari == 0:
                r.append((0, 0))
            else:
                r.append((amari, amari - nn))
            
            
            
            
        
        r = sorted(r, key=lambda a: a[0])
        ss = sum(a for a, _ in r)
        sss = ss // nn
        rsum = sum(a for a, b in r[:-sss])
        lsum = -sum(b for _, b in r[-sss:])
        vvv = max(rsum, lsum)
        
        if vvv <= K:
            return True
        else:
            return False

    sq = int(math.sqrt(SUM))
    aaa = []
    for n in range(1, sq + 1):
        
        if SUM % n != 0:
            continue
        aaa.append(n)
        ddd = SUM // n
        
        if check(ddd):
            print(ddd)
            return
        

    for n in reversed(aaa):
        
        if check(n):
            print(n)
            return
        


if __name__ == '__main__':
    main()

Solution (Python):


from heapq import heappush, heapreplace
from itertools import count, product
from functools import reduce
from math import ceil, sqrt
from collections import defaultdict, deque

class Primes_C(object):
    def b_search(L,t):
        
        search_range = [-1, len(L)]
        update_range = lambda mid: search_range.__setitem__(t<L[mid], mid)
        for _ in range(search_range[1].bit_length()):
            update_range(sum(search_range)//2)
        return search_range[0]
    
    def __init__(self):
        self.P = [2]
        self.Pappend = self.P.append
        self.Q = deque([])
        self.Qappend = self.Q.append
        self.Qpopleft = self.Q.popleft
        self.hq = [] 
        self.integer = count(3,2)
        self.current_i = 2
        self.valid_range = 1
        self.iter_index = 0

    def __iter__(self):
        return self

    def __next__(self):
        if self.iter_index >= len(self.P):
            self.step_calc(1)
        self.iter_index += 1
        return self.P[self.iter_index-1]
        pass

    def iter_reset(self, index=0):
        self.iter_index = index

    def list(self, max_int=None):
        if max_int is None:
            return self.P[:]

        if  max_int <= self.current_i:
            return self.P[:Primes_C.b_search(self.P,max_int)+1]

        else:
            self.calc(max_int)
            return self.P[:]

    def extend(self, i):
        if i >= self.valid_range:
            if self.Q:
                q = self.Qpopleft()
                heappush(self.hq, (q**2,q))
            self.valid_range = self.Q[0]**2 if self.Q else i**2

    def check_update(self,i):
        m,r = self.hq[0] if self.hq else (0,0)
        flag =  (i != m)
        if flag:
            self.Pappend(i)
            self.Qappend(i)
        while m == i:
            heapreplace(self.hq, (m+2*r, r))
            m,r = self.hq[0]
        return flag

    def calc(self, max_int):
        for i in self.integer:
            self.extend(i)
            self.check_update(i) 
            self.current_i = i+1
            if max_int <= self.current_i:
                break

    def step_calc(self, step):
        for i in self.integer:
            self.extend(i)
            step -= self.check_update(i) 
            self.current_i = i+1
            if not step:
                break

    def factorization(self, m, F=defaultdict(int)):
        max_int = ceil(sqrt(max(m, 0)))
        index0 = len(self.P)
        index = 0
        p = self.P[0]
        while m > 1 and p <= max_int:
            while not m%p:
                m //= p
                F[p] += 1

            index += 1
            if index >= index0:
                self.step_calc(1)
            p = self.P[index]

        if m > 1:
            F[m] += 1

        return F



def solve():
    N, K = map(int, input().split())
    A = tuple(map(int, input().split()))
    Primes = Primes_C()

    F = Primes.factorization(sum(A))
    res = 1
    for q in product(*[[p**m for m in range(F[p]+1)] for p in F]):
        d = reduce(int.__mul__, q)
        B = sorted([a%d for a in A])
        if sum(B)-sum(B[-(sum(B)//d):]) <= K:
            res = max(res, d)

    return str(res)

if __name__ == '__main__':
    print(solve())

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

total = 0
for _a in a:
    total += _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)

    divisors.sort()

    return divisors[::-1] 

d_all = make_divisors(total)

for d in d_all:
    resid = []
    for i in range(n):
        resid.append(a[i] % d)
    resid_sum = sum(resid)
    resid.sort()
    x = resid_sum // d

    if x > 0:
        resid_sum2 = sum(resid[:-x]) + x * d - sum(resid[-x:])
        if resid_sum2 <= k * 2: 
            ans = d
            break
    else:
        ans = d
        break

print(ans)

Solution (Python):

def inpl(): return map(int, input().split())
from itertools import accumulate
from bisect import bisect, bisect_left
from collections import Counter, deque
from functools import reduce
from itertools import accumulate
from operator import itemgetter, xor

from sys import setrecursionlimit
setrecursionlimit(10**9)
 
import sys

from collections import Counter
def inpl(): return list(map(int, input().split()))

N, K = inpl()
A = inpl()

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

D = sorted(make_divisors(sum(A)))

ans = 1
g0 = itemgetter(0)

for d in D:
    x = 0
    X = []
    for i in range(N):
        X.append(A[i]%d)

    X = sorted(X)
    l = 0
    r = N-1
    while l < N and X[l] == 0:
        l += 1
    while l < N and (not (X[l] == 0 or X[l] == d)):
        m = min(X[l], d - X[r])
        x += m
        X[l] -= m
        X[r] += m
        if X[l] == 0:
            l += 1
        if X[r] == d:
            r -= 1
    if x <= K:
        ans = max(ans, d)

print(ans)

Solution (Python):
import sys
n,k=map(int,input().split())
a=list(map(int,input().split()))

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
d=make_divisors(sum(a))
l=len(d)

x=0
for i in range(l):
    b=[]
    c=[]
    x=d[i]
    for j in range(n):
        if x-a[j]%x>a[j]%x:
            b.append(a[j]%x)
        else:
            c.append(x-a[j]%x)
    b.sort()
    c.sort()
    bs=sum(b)
    cs=sum(c)
    if bs<cs:
        bufl=b
        b=c
        c=bufl
        buf=bs
        bs=cs
        cs=buf

    while(bs>cs):
        y=b.pop(-1)
        bs-=y
        cs+=(x-y)
        c.append(y)
    if bs-cs==0 and bs<=k:
        print(x)
        sys.exit()

Solution (Python):
N, K = map(int, input().split())
A = list(map(int, input().split()))
INF = (10 ** 6)*500

M = 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)

    divisors.sort(reverse=True)
    return divisors

T = make_divisors(M)

ans = INF
for t in T:
    p = []
    for a in A:
        p.append(a - a//t * t)
    p.sort()
    s, w = 0, 0
    for h in p:
        if s + h <= K:
            s += h
        else:
            w += t - h
    if s >= w:
        ans = t
        break

print(ans)

Solution (Python):
n,K=map(int,input().split())
d_=[]
a=[int(i) for i in input().split()]
S=sum(a)

i=1
while i*i<=S:
  if S%i==0:
    d_.append(i)
    d_.append(S//i)
  i+=1

d_.sort()
for d in d_[::-1]:
  b=[]
  B=0
  for i in range(n):
    b.append(a[i]-d*(a[i]//d))
    B+=b[-1]
  b.sort()
  
  flag=False
  for k in range(n+1):
    if sum(b[0:k])<=min(K,K+B-d*(n-k)):
      flag=True
      break
  if flag:
    break
print(d)

Solution (Python):
N,K=map(int,input().split())
A=[int(i) for i in input().split()]
S=sum(A)
DivS=set()
index=1
while(index*index<=S):
    if S%index==0:
        DivS.add(index)
        DivS.add(S//index)
    index+=1

ans=1
for d in DivS:
    B=[A[i] for i in range(N)]
    for i in range(N):
        if A[i]%d==0:
            continue
        
        
        tmp1=(A[i]//d)*d
        tmp2=tmp1+d
        if abs(tmp1-A[i])<=abs(tmp2-A[i]):
            B[i]=tmp1
        else:
            B[i]=tmp2
    nowsum=sum(B)
    
    if nowsum!=S:
        C=sorted(range(N),key=lambda i:abs(A[i]-B[i]),reverse=True)
        if nowsum>S:
            k=0
            need=(nowsum-S)//d
            for i in C:
                if B[i]>A[i]:
                    B[i]-=d
                    k+=1
                if k>=need:
                    break
        if nowsum<S:
            k=0
            need=(S-nowsum)//d
            for i in C:
                if B[i]<A[i]:
                    B[i]+=d
                    k+=1
                if k>=need:
                    break
    
    cost=sum([abs(A[i]-B[i]) for i in range(N)])
    if cost<=2*K:
        ans=max(ans,d)
print(ans)

Solution (Python):

import sys
INF = float("inf")


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 solve(N: int, K: int, A: "List[int]"):
    tot = sum(A)
    divs = make_divisors(sum(A))

    m = 1
    for cand in divs[1:]:
        modA = sorted([a % cand for a in A])
        counter = 0
        left = 0
        while left < N and modA[left] == 0:
            left += 1
        right = N-1
        while left < right:
            smaller = min(modA[left], cand - modA[right])
            modA[left] -= smaller
            modA[right] += smaller
            counter += smaller
            if modA[left] == 0:
                left += 1
            if modA[right] == cand:
                right -= 1
        if counter <= K:
            m = cand

    print(m)

    return


def main():

    def iterate_tokens():
        for line in sys.stdin:
            for word in line.split():
                yield word
    tokens = iterate_tokens()
    N = int(next(tokens))  
    K = int(next(tokens))  
    A = [int(next(tokens)) for _ in range(N)]  
    solve(N, K, A)


if __name__ == '__main__':
    main()

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

sm = sum(a)

div = []
for i in range(1,int(sm**0.5)+1):
    if sm % i == 0:
        div.append(i)
        if i != (sm // i):
            div.append(sm//i)
div.sort()

answer = 1

for _ in range(len(div)):
    ans = div.pop()
    b = sorted(list(map(lambda x: x%ans, a)))

    lenb = len(b)
   
    l = 0
    r = ans*len(b) - sum(b)

    for i in range(lenb):
        l += b[i]
        r -= ans - b[i]
        if l <= k and l >= r and (l-r) %2 ==0:
            print(ans)
            exit()

Solution (Python):
import math
import sys

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

s=sum(a)
s_factors=[]

l=int(math.sqrt(s))

for i in range(1,l+1):
    if s%i==0:
        s_factors.append(i)
        s_factors.append(s//i)

s_factors.sort()

for f in s_factors[::-1]:
    b=[a[i]%f for i in range(n)]
    c=[f-a[i]%f for i in range(n)]
    
    b.sort()
    c.sort()
    c=c[::-1]

    sb=[0 for i in range(n)]
    sc=[0 for i in range(n)]
    
    sb[0]=b[0]
    sc[0]=c[0]

    for i in range(1,n):
        sb[i]=sb[i-1]+b[i]

    for i in range(1,n):
        sc[i]=sc[i-1]+c[i]

    for i in range(n):
        if sb[i]==sc[n-1]-sc[i]:
            if sb[i]<=k:
                print(f)
                sys.exit()

Solution (Python):

from collections import defaultdict,deque
from heapq import heappush, heappop
import sys, math, bisect, random, itertools
sys.setrecursionlimit(10**5)
input = sys.stdin.readline
sqrt = math.sqrt
bisect_left = bisect.bisect_left
bisect_right = bisect.bisect_right
def LI(): return list(map(int, input().split()))
def LF(): return list(map(float, input().split()))
def LI_(): return list(map(lambda x: int(x)-1, input().split()))
def II(): return int(input())
def IF(): return float(input())
def LS(): return list(map(list, input().split()))
def S(): return list(input().rstrip())
def IR(n): return [II() for _ in range(n)]
def LIR(n): return [LI() for _ in range(n)]
def FR(n): return [IF() for _ in range(n)]
def LFR(n): return [LI() for _ in range(n)]
def LIR_(n): return [LI_() for _ in range(n)]
def SR(n): return [S() for _ in range(n)]
def LSR(n): return [LS() for _ in range(n)]
mod = 1000000007
inf = float('INF')


def A():
    a, b, c = LI()
    print(c - min(b + c, a) + b)
    return


def B():
    n = II()
    ans = 0
    for i in range(1, n + 1):
        if len(str(i)) % 2:
            ans += 1
    print(ans)
    return


def C():
    n = II()
    h = LI()
    h = h[::-1]
    for i in range(1, n):
        if h[i] <= h[i-1]:
            continue
        if h[i] == h[i - 1] + 1:
            h[i] -= 1
            continue
        print("No")
        return
    print("Yes")
    return


def D():
    s = S()
    lens = len(s)
    ans = [0] * len(s)
    i = 0
    while i != len(s):
        for j in range(i, lens):
            if s[j] == "R":
                continue
            break
        R = j - i
        for i in range(j, lens):
            if s[i] == "L":
                continue
            break
        else:
            i += 1
        L = i - j
        ans[j] = R // 2 + (L+1) // 2
        ans[j - 1] = L // 2 + (R+1) // 2

    print(*ans)
    return


def E():
    def make_divisor(n):
        res = []
        for i in range(1, int(math.sqrt(n))+1):
            if n % i == 0:
                res.append(i)
                res.append(n // i)
        if n == math.sqrt(n)** 2:
            res.append(int(math.sqrt(n)))
        return res
    n, k = LI()
    a = LI()
    x = sum(a)
    maxa = max(a)
    lis = make_divisor(x)
    lis.sort(reverse=True)
    for li in lis:
        l1 = list(map(lambda x: x % li, a))
        l2 = list(map(lambda x: - x % li, a))
        l1.sort()
        l2.sort()
        c = 0
        while 0 in l1:
            l1.remove(0)
            c += 1
        while 0 in l2:
            l2.remove(0)
        l = 0
        r = 0
        b = 0
        rx = 0
        lx = 0
        while l + r < n - c:
            if b < 0:
                b += l2[r]
                rx += l2[r]
                r += 1
            else:
                b -= l1[l]
                lx += l1[l]
                l += 1
        if b == 0 and rx <= k:
            print(li)
            return
    return


def F():
    return


if __name__ == '__main__':
    E()

Solution (Python):


def divisor_list(N): 
    res = []
    i = 1
    while i*i < N:
        if N%i == 0:
            res.append(i)
            res.append(N//i)
        i += 1
    if i*i == N: res.append(i)
    return sorted(res)

import sys
sys.setrecursionlimit(10**6)
readline = sys.stdin.readline 

n,k = [int(i) for i in readline().split()]
aaa = [int(i) for i in readline().split()]


l = list(reversed(divisor_list(sum(aaa))))


def check(x):
    res = []
    for ai in aaa:
        c = ai%x
        d = ai%x-x
        if abs(c) > abs(d): res.append(d)
        else: res.append(c)
    res.sort(key = abs)
    
    d = sum(res)
    if d > 0:
        idx = -1
        while d > 0:
            if res[idx]>0:
                d -= x
                res[idx] -= x
            idx -= 1
    elif d < 0:
        idx = -1
        while d < 0:
            if res[idx]<0:
                d += x
                res[idx] += x
            idx -= 1
                
    c = sum([i for i in res if i > 0])        


    return (c <= k)



for x in l:
    if check(x):
        print(x)
        exit()

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

mint = sum(a)
divs = []
for i in range(1, int(mint ** 0.5) +1):
    if mint % i == 0:
        divs.append(i)
        if i != mint // i:
            divs.append(mint // i)
divs.sort()
divs = divs[::-1]
result = 1
for i in range(len(divs)-1):
    cur = divs[i]
    sums = 0
    divList = []
    for j in range(n):
        numi = a[j] % cur
        sums += numi
        divList.append(numi)
    divList.sort()
    divList = divList[::-1]
    count = sums
    countV = 0
    for j in range(n):
        count -= divList[j]
        countV += cur - divList[j]
        if count == countV:
            break
    if count <= k:
        result = cur
        break

print(result)

Solution (Python):

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

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

sumA = sum(A)

now = 1
yaku = []

while True:

    if now ** 2 > sumA:
        break

    if sumA % now == 0:
        yaku.append(now)
        yaku.append(sumA // now)

    now += 1

yaku.sort()

nowK = 0
nowX = 0
flag = True
ans = 0
for i in yaku:

    nowK = 0
    nowX = 0
    flag = True
    nlis = []
    for a in A:

        nowK += a % i
        nlis.append(a%i)

    nlis.sort()
    nlis.reverse()

    for j in range(nowK // i):

        nowX += i - nlis[j]

    if nowX > K:
        flag = False
        


            
    if flag:
        ans = max(ans,i)

print (ans)

Solution (Python):
N, K = map(int, input().split())
A = list(map(int, input().split()))
sumA = 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)
    divisors.sort(reverse=True)
    return divisors

divs = make_divisors(sumA)

for i in divs:
    mod = []
    for j in range(N):
        mod.append(A[j] % i)
    mod.sort(reverse=True)
    tmp = sum(mod) // i 
    tmp = tmp * i - sum(mod[:tmp])  
    if tmp <= K:
        ans = i
        break

print(ans)

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

    
    return divisors

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

s = sum(a)

divs = make_divisors(s)
divs.sort(reverse=True)


divstimes = len(divs)

for i in range(divstimes):
    nowd = divs[i]
    rems = [a[j]%nowd for j in range(n)]
    rems.sort(reverse=True)
    time = sum(rems)//nowd
    
    
    total = sum(rems[time:n])
    
    
    if(total <= k):
        ans = nowd
        break
    
    
print(ans)

Solution (Python):


import sys

n, k = map(int, input().split())
a = list(map(int, input().split()))
s = sum(a)
l = []

def check(b) :
    r1 = [x % b for x in a]
    r1.sort()
    s1 = sum(r1)
    
    mn = 1e9
    s2 = 0
    for i in range(n):
        s2 += r1[i]
        mn = min(max(s2, (n-1-i)*b - (s1-s2)), mn)
        
    if mn <= k :
        print(int(b))
        sys.exit(0)
        

for p in range(1,int((s+1)**0.5+1)) :
    if s % p != 0:
        continue
    b = s // p
    l.append(p)
    check(b)
    
l.reverse()

for b in l:
    check(b)

Solution (Python):
N, K = map(int, input().split())
A = list(map(int, input().split()))
A_sum = 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)

    divisors.sort(reverse=True)
    return divisors

cand = make_divisors(A_sum)
temp = 0
for i in range(len(cand)):
    c = cand[i]
    abs_sum = 0
    temp = []
    for j in range(len(A)):
        temp.append(A[j] % c)
        
    temp_sum = sum(temp)
    num = temp_sum // c
    temp.sort(reverse=True)
    for i in range(num):
        temp[i] = c - temp[i]

    abs_sum = sum(temp)
    if abs_sum <= 2*K:
        print(c)
        exit()

print(1)

Solution (Python):

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







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

dvs = make_divisors(sum(A))

AA = [None for i in range(N)]
ok = 1
for dv in dvs:
    for i in range(N):
        AA[i] = A[i]%dv
    AA = sorted(AA)
    
    l,r = 0,N-1
    while l < N-1 and AA[l] == 0:
        l+=1
    while r > 0 and AA[r] == 0:
        r-=1
    kcnt = 0
    while l<r and r>0 and l<N-1:
        
        
        if AA[l] == 0:
            l+=1
        if AA[r]%dv == 0:
            r-=1
        else:
            mv = max(min([AA[l],dv-AA[r],K-kcnt]),0)
            kcnt += mv
            AA[l]-=mv
            AA[r]+=mv
        if mv == 0:
            
            break
    if l>=r:
        ok = max(ok, dv)




print(ok)

Solution (Python):
from collections import defaultdict, deque
n, k = map(int, input().split())
a = list(map(int, input().split()))
s = sum(a)

x = []
for i in range(1, s+1):
    if i * i > s:
        break
    if s % i == 0:
        x.append(i)
        x.append(s//i)

ans = 0
for xi in x:
    b = []
    for i in range(n):
        if a[i] % xi != 0:
            b.append(a[i] % xi)

    b.sort()
    b = deque(b)

    c = 0
    r = 0
    while b:
        q = b.pop() + r

        while q < xi:
            p = b.popleft()
            q += p
            c += p

        r = q - xi

    if c <= k:
        ans = max(ans, xi)
    

print(ans)

Solution (Python):
n,k = map(int,input().split())
a = list(map(int,input().split()))
sun = sum(a)
cd = []
rcd = []
for i in range(1,int(sun**0.5)+1):
  if sun % i == 0:
    cd.append(i)
    rcd.append(sun//i)
rcd.reverse()
if cd[-1] == rcd[0]:
  del cd[-1]
gcd = cd + rcd
gcd.reverse()

count = -1
while True:
  count += 1
  g = gcd[count]
  b = list(map(lambda x: x % g,a))
  moon = sum(b)
  luna = moon // g
  b.sort()
  score = sum(b[:n-luna])
  if score <= k:
    print(g)
    break