#include <bits/stdc++.h>
using namespace std;
const int maxn = 1e6 + 10;
const long long mod = 1e9 + 7;
int n, a[maxn], b[maxn];
long long c[maxn], d[maxn], s0, s, ans;
void chk(long long x) {
  long long ss = 0, mi, la, pp, t = 0;
  for (int i = 1; i <= n; i++) {
    t += b[i] / x;
    a[i] = b[i] % x;
  }
  for (int i = 1; i <= n; i++) {
    if (!a[i]) continue;
    la = a[i];
    int j = i;
    while (j < n && la < x) la += a[++j];
    pp = la - x;
    a[j] -= pp;
    c[i - 1] = 0;
    for (int k = i; k <= j; k++) c[k] = c[k - 1] + a[k];
    for (int k = i; k <= j; k++) c[k] += c[k - 1];
    d[j + 1] = 0;
    for (int k = j; k >= i; k--) d[k] = d[k + 1] + a[k];
    for (int k = j; k >= i; k--) d[k] += d[k + 1];
    mi = c[i - 1] + d[i + 1];
    for (int k = i + 1; k <= j; k++) mi = min(mi, c[k - 1] + d[k + 1]);
    ss += mi;
    t++;
    if (t == s0 / x) break;
    a[j] = pp;
    i = j - 1;
  }
  ans = min(ans, ss);
}
int main() {
  int i, j;
  cin >> n;
  for (i = 1; i <= n; i++) {
    scanf("%d", &b[i]);
    s += b[i];
  }
  if (s == 1) {
    cout << "-1\n";
    return 0;
  }
  s0 = s;
  ans = s * n;
  for (i = 2; (long long)i * i <= s; i++) {
    if (s % i == 0) {
      chk(i);
      while (s % i == 0) s /= i;
    }
  }
  if (s > 1) chk(s);
  cout << ans << "\n";
  return 0;
}
