#include <bits/stdc++.h>
using namespace std;
void _in(long long *a, ...) {
  va_list arg_ptr;
  scanf("%I64d", a);
  long long *temp;
  va_start(arg_ptr, a);
  temp = va_arg(arg_ptr, long long *);
  while (temp) {
    scanf("%I64d", temp);
    temp = va_arg(arg_ptr, long long *);
  }
  va_end(arg_ptr);
}
void _in(int *a, ...) {
  va_list arg_ptr;
  scanf("%d", a);
  int *temp;
  va_start(arg_ptr, a);
  temp = va_arg(arg_ptr, int *);
  while (temp) {
    scanf("%d", temp);
    temp = va_arg(arg_ptr, int *);
  }
  va_end(arg_ptr);
}
const long long N = 1e6 + 100;
const long long INF = 0x3f3f3f3f3f3f3f3f;
long long a[N], n, v, na[N];
vector<long long> prim;
bool vis[N];
set<long long> S;
long long work(long long l, long long r, long long p) {
  long long m = l - 1, sum = 0;
  long long res = 0;
  while (sum <= p / 2 && m < r) {
    sum += na[++m];
  }
  for (int i = (int)l; i <= (int)r; i++) {
    res += na[i] * abs(m - i);
  }
  return res;
}
long long count(long long p) {
  for (int i = (int)1; i <= (int)n; i++) na[i] = a[i] % p;
  long long l, r, res = 0;
  l = 1;
  while (l <= n) {
    long long sum = 0;
    r = l - 1;
    while (sum < p && r < n) {
      sum += na[++r];
    }
    if (!sum) break;
    na[r] -= sum - p;
    res += work(l, r, p);
    na[r] = sum - p;
    if (na[r])
      l = r;
    else
      l = r + 1;
  }
  return res;
}
void inti() {
  long long _n = sqrt(v);
  for (int i = (long long)2; i <= (long long)_n; i++) {
    if (!vis[i]) {
      prim.push_back(i);
      long long k = i * 2;
      while (k <= _n) {
        vis[k] = 1;
        k += i;
      }
    }
  }
}
void cps(long long x) {
  int len = prim.size();
  for (int i = (int)0; i <= (int)len - 1; i++) {
    if (x / prim[i] * prim[i] == x) S.insert(prim[i]);
  }
}
void cp(long long x) {
  if (x <= sqrt(v)) {
    cps(x);
    return;
  }
  for (int i = (int)sqrt(x); i >= (int)1; i--) {
    if (x / i * i == x) {
      if (i == 1) {
        S.insert(x);
        return;
      }
      cp(x / i);
      cp(i);
      return;
    }
  }
}
int main() {
  ios::sync_with_stdio(false);
  cin.tie(0);
  cout.tie(0);
  cin >> n;
  for (int i = (int)1; i <= (int)n; i++) {
    cin >> a[i];
    v += a[i];
  }
  if (v == 1) {
    cout << -1;
    exit(0);
  }
  long long ans = INF;
  inti();
  cp(v);
  for (auto it : S) {
    ans = min(ans, count(it));
  }
  cout << ans;
  return 0;
}
