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):
def main(sample_file = ''):

    """ convenient functions
    
    
    
    
    
    """

    """convenient decorator
    
    
        
        
        
        
        
        
        
        
        
        
    """
    
    
    import sys
    sys.setrecursionlimit(10**7)
    from itertools import accumulate, combinations, permutations, product 
    
    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 = []  
        b, e = 2, 0  
        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
        """
        
        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 
    from heapq import heapify, heappop, heappush, heappushpop, heapreplace,nlargest,nsmallest 
    from copy import deepcopy, copy 
    import operator
    from operator import itemgetter 
    
    
    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 
    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)

    
    
    INF = 10 ** 18
    MOD = 10 ** 9 + 7
    modpow = lambda a, n, p = MOD: pow(a, n, p) 
    def modinv(a, p = MOD):
        
        
        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):
        
        
        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
    
        
        
    
        
        
        
        
        
        
        
    
        
        
        
        
    
        
        
    """

    
    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
    
    
    
    
    
    
    
    """

    
    if sample_file:
        sys.stdin = open(sample_file)
        
    
    

    N, K = R()
    A = R()
    A.sort(reverse=True)
    Remain = [0] * N
    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
    
    divisors = make_divisors(sumA)
    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
        
    
    

    """memo: how to use defaultdict of list
    
    Dic = defaultdict(list)
    
    Dic[x].append(y)
    
    for k, v in Dic.items():
    """
    
    """memo: how to solve binary problems
    
    >>> a = 5
    >>> bin_str_a = format(a, '
    >>> print(bin_str_a)
    0b0101 
    """
    
    """memo: how to solve the problem
    creating simple test/answer
    greed
    simple dp
    graph
    """

if __name__ == '__main__':
    main()

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(reverse=True)
    return divisors

def checker(A,k):
    A.sort(reverse=True)
    if sum(A[sum(A) // d:]) <= k:
        return True
    return False

n,k = [int(x) for x in input().split()]
A = [int(x) for x in input().split()]

for d in make_divisors(sum(A)):
    buf = []
    for a in A:
        buf.append(a%d)
    
    if checker(buf,k):
        print(d)
        break

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

sumA = sum(A)
divisors = []
for i in range(1, sumA + 1):
    if i * i > sumA:
        break
    if sumA % i != 0:
        continue
    divisors.append(i)
    if sumA // i != i:
        divisors.append(sumA // i)

divisors.sort(reverse=True)

for d in divisors:
    
    
    
    
    
    
    
    
    
    costs = [a % d for a in A]
    costs.sort(reverse=True)
    if sum(costs[sum(costs) // d:]) <= K:
        print(d)
        break

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

sumA = sum(A)
divisors = []
for i in range(1, sumA + 1):
    if i * i > sumA:
        break
    if sumA % i != 0:
        continue
    divisors.append(i)
    if sumA // i != i:
        divisors.append(sumA // i)

divisors.sort(reverse=True)

ans = 0
for d in divisors:
    costs = [a % d for a in A]
    costs.sort(reverse=True)
    plus = sum(costs)
    minus = 0
    for j in range(N):
        if plus == minus:
            break
        else:
            plus -= costs[j]
            minus += d - costs[j]

    if plus <= K:
        print(d)
        break

Solution (Python):


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

sum_a = sum(A)


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

dc_list.sort(reverse = True)

for d in dc_list:
    mods = [a % d for a in A]
    mod_sum = sum(mods)
    if mod_sum % d != 0:
        continue
    mods = sorted(mods)

    op = 0
    mod_len = len(mods)
    for i, mod in enumerate(mods):
        op += mod

        if op > K:
            break

        if (mod_len - (i + 1)) * d == mod_sum and op <= K:
            print(d)
            exit(0)

Solution (Python):
import math

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

def cost(d,numList):
    r = [x%d for x in numList]
    r.sort(reverse=True)
    p = sum(r)//d
    c = 0
    for i in range(p):
        c += d - r[i]
    return(c)

def divisors(n):
    sq = math.ceil(math.sqrt(n))
    ans = []
    for i in range(1,sq):
        if n%i == 0:
            ans.append(i)
            ans.append(n//i)
    return(ans)

divs = divisors(sum(A))
ans = 1
for d in divs:
    c = cost(d, A)
    if c <= K:
        ans = max(ans,d)
print(ans)

Solution (Python):
import math,string,itertools,fractions,heapq,collections,re,array,bisect,sys,random,time
sys.setrecursionlimit(10**7)
inf = 10**20

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

def distance(x,d):
    r = x%d
    return(min(r,d-r))

def cost(d,numList):
    r = list(map(lambda x: x%d, numList))
    r.sort(reverse=True)
    p = sum(r)//d
    c = 0
    for i in range(p):
        c += d - r[i]
    return(c)

def divisors(n):
    sq = math.ceil(math.sqrt(n))
    ans = []
    for i in range(1,sq):
        if n%i == 0:
            ans.append(i)
            ans.append(n//i)
    return(ans)

s = sum(A)
divs = divisors(s)
ans = 1
for d in divs:
    c = cost(d, A)
    if c <= K:
        ans = max(ans,d)
print(ans)

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

sum_a = sum(a)
divisors = []
for i in range(1,int(sum_a**0.5)+1):
    if sum_a % i == 0:
        divisors.append(i)
        if i != n // i:
            divisors.append(sum_a//i)

divisors.sort(reverse=True)

for i in range(len(divisors)):
    b = [0]*n
    for j in range(n):
        b[j] = a[j] % divisors[i]
    b.sort(reverse=True)
    plus = sum(b)
    minus = 0
    for j in range(n):
        if plus == minus:
            break
        else:
            plus -= b[j]
            minus += (divisors[i] - b[j])
    if plus <= k:
        print(divisors[i])
        break

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


def divisor(N):
    from math import sqrt
    D = []
    for i in range(1, int(sqrt(N)) + 1):
        if N % i == 0:
          D.append(i)
          D.append(N // i)

    return list(set(D))

s = sum(A)
divisors = divisor(s)
divisors.sort(reverse=True)

pride = 0
tention = 0
TKM = []
for d in divisors:
    for i, a in enumerate(A):
        l = -(a % d)
        h = d - (a % d)
        TKM.append((h, l))

    hekinan = sorted(TKM, key=lambda shisho: abs(shisho[0]))
    if abs(hekinan[0][0]) <= abs(hekinan[-1][1]):
        pride += abs(hekinan[0][0])
        tention += hekinan[0][0]
        hekinan = hekinan[1:]
    else:
        pride += abs(hekinan[-1][1])
        tention += hekinan[-1][1]
        hekinan = hekinan[:-1]
    while len(hekinan) != 0:
        if tention >= 0:
            pride += abs(hekinan[-1][1])
            tention += hekinan[-1][1]
            hekinan = hekinan[:-1]
        else:
            pride += abs(hekinan[0][0])
            tention += hekinan[0][0]
            hekinan = hekinan[1:]

    if pride // 2 <= K:
        print(d)
        break
    pride = 0
    tention = 0
    TKM = []

Solution (Python):

import sys
import math
INF = 1 << 20

def main():
    N, K = [int(i) for i in sys.stdin.readline().strip().split()]
    numbers = [int(i) for i in sys.stdin.readline().strip().split()]
    print("%d" % solve(N, K, numbers))


def solve(N, K, numbers):

    total = sum(numbers)
    ans = 1
    candidates = []
    
    divisor = 1
    
    while divisor * divisor <= total:
        if total % divisor == 0:
            candidates.append(divisor)
            candidates.append(total/divisor)
        divisor += 1
    candidates = sorted(candidates, reverse=True)

    for divisor in candidates:
        mods = []
        for number in numbers:
            mods.append(number % divisor)
        mods.sort()
        A = sum(mods)

        need = INF
        index = math.floor(-1 * A/divisor)
        need = sum(mods[0:index])
        if need <= K:
            ans = max(ans, divisor)

    return ans


if __name__ == "__main__":
    main()

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

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

ans = 0

for i in divisors:
    listA = [0]*N
    for j in range(N):
        listA[j] = A[j] % i
    listA.sort()
    sumlist = sum(listA)


    if sum(listA[:-sumlist // i]) <= K:
        ans = max(ans,i)
            
print(ans)

Solution (Python):



import sys
import math
import bisect
sys.setrecursionlimit(1000000000)
from heapq import heappush, heappop
from collections import defaultdict
from itertools import accumulate
from collections import Counter
from collections import deque
from operator import itemgetter
from itertools import permutations
mod = 10**9 + 7

n,k = map(int,input().split())
a = list(map(int,input().split()))
s = sum(a)
lst = []
for i in range(1,int(math.sqrt(s))+1):
    if s % i == 0:
        if i != s//i:
            lst.append(i)
            lst.append(s//i)
        else:
            lst.append(i)
lst.sort()
for i in lst[::-1]:
    x = [[j%i,-j%i] for j in a]
    x.sort()
    b = [j for j,k in x]
    c = [k for j,k in x]
    
    b = list(accumulate(b))
    
    c = list(accumulate(c))
    for j in range(n-1):
        if b[j] == c[-1]-c[j]:
            ans = b[j]
            break
    if ans <= k:
        print(i)
        break

Solution (Python):
import math
N,K = map(int,input().split())
A_s = list(map(int,input().split()))
S = sum(A_s)
divs = []
for i in range(1, round(math.sqrt(S)+1) ):
    if S%i==0:
        divs.append(i)
        divs.append(S//i)
answer = 1
for div in divs:
    r_s = []
    for A in A_s:
        r_s.append(A%div)
    r_s.sort()
    if sum(r_s[:-sum(r_s)//div]) <= K and answer < div:
        answer = div
    
    

print(answer)

Solution (Python):

import math

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

P = [1,S]
for k in range(2,math.floor(math.sqrt(S))+1):
    if S % k == 0:
        P.append(k)
        P.append(S//k)
P = sorted(P)[::-1]

for e in P:
    t = []
    u = []
    for a in A:
        if a%e != 0:
            t.append(a%e)
            u.append(e-a%e)
    t = sorted(t)
    if len(t) == 0:
        print(e)
        exit(0)
    else:
        p = [f for f in t]
        for k in range(1,len(t)):
            p[k] += p[k-1]
        m = [e-f for f in t]
        for k in range(1,len(t)):
            m[-k-1] += m[-k]
        for k in range(len(t)-1):
            if p[k] == m[k+1] and p[k] <= K:
                print(e)
                exit(0)

Solution (Python):
import math
N, K = map(int, input().split())

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



A_sum = sum(A_array)

candidate_array = []

for i in range(1, int(math.sqrt(A_sum))+1):
    if A_sum % i == 0:
        candidate_array.append(i)
        if A_sum // i != i:
            candidate_array.append(A_sum//i)

candidate_array.sort()

ans = 0

for check_num in candidate_array:
    q_array = [a % check_num for a in A_array]
    q_array.sort()
    
    start = 0
    rest = N * check_num - sum(q_array)
    for q in q_array:
        start += q
        rest -= (check_num-q)
        
        if start == rest:
            break
    if start <= K:
        ans = max(ans, check_num)

print(ans)

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

sum1 = 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

li = make_divisors(sum1)

ans = 0

for i in li:
    b = sorted(list(map(lambda x: x % i,a)))
    count = 0
    flag = -1
    for j in range(len(b)):
        if b[j] % i != 0:
            count += b[j]
            while b[j] > 0:
                if b[j] + b[flag] < i:
                    b[flag] += b[j]
                    b[j] = 0
                else:
                    b[j] -= i - b[flag]
                    b[flag] = i
                    flag -= 1
    if count <= k:
        ans = max(ans,i)
print(ans)

Solution (Python):
import sys
import math

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


def ok(x):
    b = [i % x for i in a]
    b.sort(reverse=True)
    t = int(sum(b) / x)
    if t == 0:
        return True
    return True if sum(b[t:]) <= k else False


s = sum(a)
sqs = int(math.sqrt(s))
ans = 1
for x in range(1, sqs + 1):
    if s % x != 0:
        continue
    if ok(x):
        ans = max(ans, x)
    if ok(int(s / x)):
        ans = max(ans, int(s / x))

print(ans)

Solution (Python):
import sys
import math

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


def ok(x):
    b = []
    for an in a:
        b.append(an % x)
    b.sort(reverse=True)
    print(x, a, b, file=sys.stderr)
    t = int(sum(b) / x)
    print(t, sum(b[t:]), file=sys.stderr)
    if t == 0:
        return True
    return True if sum(b[t:]) <= k else False


s = 0
for an in a:
    s += an

ans = 1
for x in range(1, int(math.sqrt(s)) + 1):
    if s % x != 0:
        continue
    if ok(x):
        ans = max(ans, x)
    if ok(int(s / x)):
        ans = max(ans, int(s / x))

print(ans)

Solution (Python):
from itertools import accumulate

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



def f(d):
    B = sorted(a % d for a in A)
    C = [d - b for b in B]
    X = list(accumulate(B))
    Y = list(accumulate(C))
    return any(
        X[j] == (Y[-1] - Y[j]) <= K
        for j in range(N)
    )



S = sum(A)
ans = max(
    (
        S // d if f(S // d) else
        d if f(d) else
        0
    )
    for d in range(1, int(S**0.5) + 2)
    if S % d == 0
)

print(ans)

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

asum = sum(a)
gcdmax = int(math.sqrt(asum))
li = []
for i in range(2,gcdmax+1):
    if asum%i==0:
        li.append(i)
for i in range(gcdmax,0,-1):
    if asum%i==0:
        li.append(asum//i)


ans = 1


for i in li:
    b = [a[ii] % i for ii in range(n)]
    b.sort()

    l = 0
    r = 0
    x = 0
    y = n-1
    while x<=y:
        if r>=l:
            l += b[x]
            x += 1
        else:
            r += i - b[y]
            y -= 1

    if max(l,r) <= k and (l-r)%i==0 :
        ans = i

print(ans)

Solution (Python):
N, K = list(map(int, input().split()))
A = list(map(int, input().split()))
s = sum(A)
flag = False
def make_divisors(n):
    divisors = []
    for i in range(int(n**0.5), 0, -1):
        if n%i == 0:
            divisors.append(i)
            if i != n//i:
                divisors.append(n//i)
    return sorted(divisors, reverse=True)
divs = make_divisors(s)
for x in divs:
    if flag:
        break
    sortedA = sorted([a%x for a in A])
    sumA = sum(sortedA)
    index_len = len(sortedA)
    sump = 0
    for i, a in enumerate(sortedA):
        sump += a
        summ = x*(index_len - (i+1)) - (sumA - sump)
        if sump == summ and sump <= K:
            print(x)
            flag = True
            break

Solution (Python):
N,K=list(map(int,input().split()))
A=list(map(int,input().split()))
S=sum(A)
facts=set()
for i in range(1,int(S**0.5)+1):
    if S%i==0:
        facts.add(i)
        facts.add(S//i)
for f in sorted(facts,key=lambda x:-x):
    rs = [i%f for i in A]
    rs2=sorted(rs)
    rsr = [f-r for r in rs2]
    if f-rs2[-1]>K and rs2[-1]>K:
        continue
    cum=0
    ruiseki=[0]*(N)
    tmp=0
    for i,a in enumerate(rs2):
        cum+=a
        ruiseki[i]=cum
    for i in range(N-1):
        s_l=ruiseki[i]
        s_h = f*(N-i-1)-(ruiseki[-1]-s_l)
        if max(s_l,s_h)<=K:
            print(f)
            break
    else:
        continue
    break

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


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


def solve(B, f):
    cost = sum(B)
    cost = sum(B[:-cost//f])
    return cost


fct = divisors(sum(A))
for f in sorted(fct, reverse=True):
    B = sorted([b % f for b in A])
    cost = solve(B, f)
    if K >= cost:
        print(f)
        quit()

Solution (Python):
import numpy as np
import sys



def solve(A, K, div):
    for d in range(div.shape[0] - 1, 0, -1):
        res = div[d]
        B = np.sort(A % res)
        if B[B.shape[0] - 1] == 0:
            return res
        i = 0
        j = B.shape[0] - 1
        cost = res - B[j]
        scost = 0
        while j - i > 0:
            for n in range(i, j):
                scost += B[n]
                if scost >= cost:
                    while scost > cost:
                        j -= 1
                        cost += res - B[j]
                    i = n + 1
                    break
            else:
                i = j
        if K >= cost:
            return res
    return 1


def divisor(d, div):
    r = int(d ** 0.5 - 0.0000001) + 1
    ind = 0
    for i in range(1, r):
        if d % i == 0:
            div[ind] = i
            ind += 1
            div[ind] = d // i
            ind += 1
    if d % r == 0:
        div[ind] = r
        ind += 1
    return ind


line = sys.stdin.readline
N, K = map(int, line().split())
A = np.fromstring(line(), dtype=np.int64, sep=' ')
d = A.sum()
div = np.empty(10 ** 6, dtype=np.int64)
num = divisor(d, div)
div = np.sort(div[:num])
print(solve(A, K, div))

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

totalA = sum(A)


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

divisors_lst = make_divisors(totalA)

for i in divisors_lst: 
    lst = []
    for j in A:
        lst.append(j % i)
    lst.sort()
    total_lst = 0
    for j in lst:
        total_lst += i - j
    tmp = 0
    for k in lst:
        tmp += k
        total_lst -= (i - k)
        if max(tmp, total_lst) <= K:
            print (i)
            exit()

Solution (Python):
import math
def check(n,a):
    l1 = []
    l2 = []
    count1 = 0
    count2 = 0
    for i in range(len(a)):
        if a[i]%n > n - a[i]%n:
            count1 = count1 + n - a[i]%n
            l1.append(n-a[i]%n)
        else:
            count2 = count2 + a[i]%n
            l2.append(a[i]%n)
    b = (count2 - count1) // n
    l1.sort(reverse=True)
    l2.sort(reverse=True)
    if b == 0:
        return count1
    elif b > 0:
        for i in range(b):
            count2 = count2 - l2[i]
        return count2
    else:
        for i in range(-1*b):
            count1 = count1 - l1[i]
        return count1
n,k = map(int,input().split())
a = list(map(int,input().split()))
p = sum(a)
l = []
for i in range(1,int(math.sqrt(p))+1):
    if p%i == 0:
        l.append(i)
        if i != p//i:
            l.append(p//i)
l.sort(reverse=True)
for i in range(len(l)):
    if check(l[i],a) <= k:
        print(l[i])
        break

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

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

s = sum(a)

dlist = []
for p in range(1,int(s**(1/2))+1):
    if s % p == 0:
        dlist.append(p)
        dlist.append(int(s/p))

anslist = []

for d in dlist:
    r = [a[_] % d for _ in range(n)]
    r.sort()

    w = [r[0]]
    for i in range(1,n):
        w.append(w[-1]+r[i])
    
    can = "no"
    for j in range(0,n):
        if max(w[j],d*(n-j-1)-w[n-1]+w[j])<=k:
            can = "yes"
            break
    if can == "yes":
        anslist.append(d)

print(max(anslist))

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)

    
    return divisors

input1 = input()
input2 = input()

N = int(input1.split()[0])
K = int(input1.split()[1])

nums = [int(s) for s in input2.split()]

divs = make_divisors(sum(nums))

possible = []

for i in divs:
    nord = [s%i for s in nums]
    nord.sort()
    mt_size = sum(nord) // i
    moves = sum(nord[0:N-mt_size])
    if moves <= K:
        possible.append(i)

print(int(max(possible)))

Solution (Python):
import math

def facts(n):
    sqrt_n = int(math.sqrt(n))
    fs = []
    fs_rev = []
    
    for i in range(1, sqrt_n + 1):
        if n % i == 0:
            fs.append(i)
            if n != i ** 2:
                fs_rev.append(n // i)
    
    fs.reverse()
    return fs_rev + fs

n, k = map(int, input().split())
ll = list(map(int, input().split()))
s = sum(ll)
fs = facts(s)

for f in fs:
    ll_f = list(map(lambda x: x % f, ll))
    ll_f.sort(reverse = True)
    ignore = sum(ll_f) // f
    keep = sum(ll_f[ignore:])

    if keep <= k:
        print(f)
        break

Solution (Python):
import sys

def input():
  return sys.stdin.readline()[:-1]

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()))

sumA = sum(A)
kouho = make_divisors(sumA)

for i in kouho:
  if sumA%i != 0:
    continue
  r = [0]*N
  for j in range(N):
    r[j] = A[j]%i
  sumr = sum(r)
  if sumr%i != 0:
    continue
  r.sort(reverse=True)
  num = 0
  for k in range(sumr//i):
    num += i-r[k]
  if num <= K:
    print(i)
    exit()

Solution (Python):
N,K=map(int,input().split())
A=list(map(int,input().split()))
def divisor(n):
    d0=[]
    d1=[]
    for i in range(1,int(n**.5)+1):
        x,y=divmod(n,i)
        if y==0:
            d0.append(i)
            d1.append(x)
    if d1[-1]==d0[-1]:
        d1=d1[:-1]
    return d0+d1[::-1]
D=divisor(sum(A))
r=1
for d in D[::-1]:
    x=sorted([a%d for a in A])
    for i in range(len(A)-1):
        x[i+1]+=x[i]
    if x[-1]%d==0 and x[-1-x[-1]//d]<=K:
        r=d
        break
print(r)