#include <bits/stdc++.h>
using namespace std;
int main() {
  ios_base::sync_with_stdio(false);
  cin.tie(NULL);
  unsigned long long n;
  cin >> n;
  vector<unsigned long long> a(n);
  for (unsigned long long i = 0; i < n; i++) cin >> a[i];
  unsigned long long total = 0;
  for (unsigned long long i = 0; i < n; i++) total += a[i];
  vector<unsigned long long> f;
  unsigned long long zd = total;
  for (unsigned long long i = 2; (i * i) <= zd; i++) {
    if (zd % i == 0) {
      f.push_back(i);
      while (zd % i == 0) {
        zd /= i;
      }
    }
  }
  if (zd != 1) f.push_back(zd);
  if (total == 1) {
    cout << -1 << '\n';
    return 0;
  }
  unsigned long long is = 900000000000000000;
  for (unsigned long long i = 0; i < f.size(); i++) {
    unsigned long long x = f[i];
    unsigned long long temp = 0;
    vector<pair<unsigned long long, unsigned long long>> z;
    unsigned long long tt = 0;
    for (unsigned long long j = 0; j < n; j++) {
      tt += a[j] % x;
      z.push_back(make_pair(j, a[j] % x));
      if (tt >= x) {
        unsigned long long left = 0;
        unsigned long long right = 0;
        unsigned long long Sr = 0;
        unsigned long long Sl = 0;
        z[z.size() - 1].second -= (tt - x);
        for (unsigned long long k = 0; k < z.size(); k++) {
          right +=
              (unsigned long long)z[k].first * (unsigned long long)z[k].second;
        }
        Sr = x;
        unsigned long long ttt = 900000000000000000;
        for (unsigned long long k = 0; k < z.size(); k++) {
          unsigned long long t2 = 0;
          right -= ((unsigned long long)z[k].first *
                    (unsigned long long)z[k].second);
          left += ((unsigned long long)z[k].first *
                   (unsigned long long)z[k].second);
          Sr -= z[k].second;
          Sl += z[k].second;
          t2 += (right - Sr * z[k].first) + (Sl * z[k].first - left);
          ttt = min(ttt, t2);
        }
        temp += ttt;
        z.clear();
        tt %= x;
        z.push_back(make_pair(j, tt));
      }
    }
    is = min(is, temp);
  }
  cout << is << '\n';
  return 0;
}
