#include <bits/stdc++.h>
using namespace std;
vector<long long> prms(long long n) {
  vector<long long> prms;
  if (n % 2 == 0) {
    prms.push_back(2);
    while (n % 2 == 0) n /= 2;
  }
  for (long long p = 3; p * p <= n; p += 2) {
    if (n % p == 0) {
      prms.push_back(p);
      while (n % p == 0) n /= p;
    }
  }
  if (n != 1) prms.push_back(n);
  return prms;
}
long long a[1000000];
int main() {
  ios_base::sync_with_stdio(false);
  cin.tie(NULL);
  long long n;
  cin >> n;
  long long sm = 0;
  for (int i = 0; i < n; i++) {
    cin >> a[i];
    sm += a[i];
  }
  if (sm == 1) {
    cout << -1 << endl;
    return 0;
  }
  vector<long long> p = prms(sm);
  long long bv = 8e18;
  for (auto x : p) {
    long long csm = 0;
    long long pi = 0;
    long long mv = 0;
    long long sc = 0;
    for (int i = 0; i < n; i++) {
      mv += csm;
      csm += a[i] % x;
      if (csm >= x) {
        long long acc = csm;
        long long oacc = 0;
        long long s = 8e18;
        long long omv = 0;
        for (int j = i; j >= pi; j--) {
          s = min(s, mv + omv);
          acc -= a[j] % x;
          mv -= acc;
          oacc += a[j] % x;
          omv += oacc;
        }
        csm -= x;
        pi = i;
        mv = 0;
        if (!csm) pi++;
        sc += s;
      }
    }
    bv = min(bv, sc);
  }
  cout << bv << endl;
  return 0;
}
