#include <bits/stdc++.h>
using namespace std;
void faster() {
  ios_base::sync_with_stdio(false);
  cin.tie(NULL);
  cout.tie(NULL);
}
const int MAXN = 1e6 + 1;
const long long INF = 1e18;
const long double pi = acos(-1);
const int dx[4] = {-1, -1, 1, 1};
const int dy[4] = {-1, 1, -1, 1};
long long n, a[MAXN], ans = INF, S, pref[MAXN], b[MAXN];
long long f(int l, int r) {
  long long cnt = 0, suff = 0, res = INF;
  for (int i = l; i <= r; ++i) {
    pref[i] = pref[i - 1] + cnt;
    cnt += b[i];
  }
  cnt = 0;
  for (int i = r; i >= l; --i) {
    suff = suff + cnt;
    res = min(res, pref[i] + suff);
    cnt += b[i];
    pref[i] = 0;
  }
  return res;
}
long long calc(long long x) {
  for (int i = 1; i <= n; ++i) {
    b[i] = a[i] % x;
  }
  long long cnt = 0, l = 0, res = 0;
  for (int i = 1; i <= n; ++i) {
    if (cnt == 0 && b[i] != 0) l = i;
    cnt += b[i];
    if (cnt >= x) {
      cnt %= x;
      b[i] -= cnt;
      res += f(l, i);
      b[i] = cnt;
      if (cnt != 0) l = i;
    }
  }
  return res;
}
int main() {
  faster();
  cin >> n;
  for (int i = 1; i <= n; ++i) {
    cin >> a[i];
    S += a[i];
  }
  if (S <= 1) {
    cout << -1;
    return 0;
  }
  for (long long i = 2; i * i <= S; ++i) {
    if (S % i == 0) {
      while (S % i == 0) S /= i;
      ans = min(calc(i), ans);
    }
  }
  if (S != 1) ans = min(calc(S), ans);
  cout << ans;
  return 0;
}
