#include <bits/stdc++.h>
using namespace std;
int n, num[1000039], tot, prime[1000039], use[1000039];
long long now, sum[1000039], dis[1000039],
    ans = (long long)0x3f3f3f3f * 0x3f3f3f3f;
void get_prime(int lim) {
  for (int a = 2; a <= lim; a++) {
    if (!use[a]) prime[++tot] = a;
    for (int b = 1; a * prime[b] <= lim && b <= tot; b++) {
      use[a * prime[b]] = 1;
      if (a % prime[b] == 0) break;
    }
  }
}
long long calc(long long k) {
  long long res = 0;
  sum[0] = dis[0] = 0;
  for (int a = 1; a <= n; a++) {
    sum[a] = sum[a - 1] + num[a] % k;
    dis[a] = dis[a - 1] + num[a] % k * a;
  }
  for (int a = 1, b, c, d; a <= n; a = c) {
    while (a <= n && sum[a] - sum[a - 1] == 0) a++;
    if (a > n) break;
    b = a;
    while (sum[b] - sum[a - 1] < (k + 1) / 2) b++;
    d = (k + 1) / 2 - sum[b - 1] + sum[a - 1];
    res += (long long)b * ((k + 1) / 2 - d) - dis[b - 1] + dis[a - 1];
    sum[b - 1] += d, dis[b - 1] += (long long)b * d;
    c = b;
    while (sum[c] - sum[b - 1] < k / 2) c++;
    d = k / 2 - sum[c - 1] + sum[b - 1];
    res += (long long)c * d + dis[c - 1] - dis[b - 1] - (long long)b * (k / 2);
    sum[c - 1] += d, dis[c - 1] += (long long)c * d;
  }
  return res;
}
int main() {
  scanf("%d", &n);
  for (int a = 1; a <= n; a++) {
    scanf("%d", &num[a]);
    now += num[a];
  }
  if (now < 2)
    printf("-1");
  else {
    get_prime(sqrt(now) + 1);
    for (int a = 1; prime[a] < now && a <= tot; a++) {
      if (now % prime[a] == 0) {
        while (now % prime[a] == 0) now /= prime[a];
        ans = min(ans, calc(prime[a]));
      }
    }
    if (now > 1) ans = min(ans, calc(now));
    printf("%I64d", ans);
  }
  return 0;
}
