#include <bits/stdc++.h>
using namespace std;
const long long MN = 1001000;
vector<long long> w;
long long pr[MN];
vector<long long> pf;
void proc(long long val) {
  if (!(val & 1)) {
    while (!(val & 1)) {
      val /= 2;
    }
    pf.push_back(2);
  }
  for (long long i = 3; i * i <= val; i += 2) {
    if (!(val % i)) {
      while (!(val % i)) {
        val /= i;
      }
      pf.push_back(i);
    }
  }
  if (val > 1) {
    pf.push_back(val);
  }
}
int main() {
  ios::sync_with_stdio(0);
  cin.tie(0);
  int n;
  cin >> n;
  w.assign(n, 0);
  pr[0] = 0;
  long long sm = 0;
  for (int i = 0; i < n; i++) {
    cin >> w[i];
    pr[i + 1] = pr[i] + w[i];
    sm += w[i];
  }
  proc(sm);
  long long ma = 1LL << 61;
  for (int pid = 0; pid < pf.size(); pid++) {
    long long sv = pf[pid];
    if (sv == 1) continue;
    long long md = -1;
    long long tot = 0;
    long long rem = 0;
    int id = 0, lag = 0;
    long long cov = 0;
    while (id < n) {
      rem += w[id];
      if ((md == -1) && (rem >= (sv + 1) / 2)) {
        md = id;
      }
      if (rem < sv) {
        id++;
      } else {
        if (md == -1) {
          md = id;
        }
        long long rv = 0;
        long long ctr = 0;
        while (1) {
          long long ad = min(w[lag] - cov, sv - rv);
          rv += ad;
          tot += ad * abs(md - lag);
          ctr += ad * abs(md - lag);
          if (rv < sv) {
            cov = 0;
            lag++;
          } else {
            cov = ad;
            break;
          }
        }
        rem = (w[lag] - cov) % sv;
        cov = w[lag] - rem;
        md = -1;
        if ((md == -1) && (rem >= (sv + 1) / 2)) {
          md = id;
        }
        id++;
      }
    }
    ma = min(ma, tot);
  }
  if (ma == (1LL << 61)) {
    cout << -1 << '\n';
  } else {
    cout << ma << '\n';
  }
}
