#include <bits/stdc++.h>
using namespace std;
const int N = 1e6 + 5;
long long n, a[N], sum, aa[N];
vector<long long> v;
void fact() {
  if (sum % 2 == 0) {
    v.push_back(2);
    while (sum % 2 == 0) sum /= 2;
  }
  for (long long i = 3; i * i <= sum; i += 2) {
    if (sum % i == 0) {
      v.push_back(i);
      while (sum % i == 0) sum /= i;
    }
  }
  if (sum > 2) v.push_back(sum);
}
long long get(vector<long long>& vv) {
  int sz = vv.size();
  vv.insert(vv.begin(), 0);
  vector<long long> suff(sz + 2, 0);
  long long pre = 0, second = 0, suf = 0, res = 1e18;
  for (int i = sz; i >= 1; i--) {
    suff[i] = suff[i + 1] + second;
    second += vv[i];
  }
  second = 0;
  for (int i = 1; i <= sz; i++) {
    pre += second;
    res = min(res, pre + suff[i]);
    second += vv[i];
  }
  return res;
}
long long solve(long long p) {
  long long tmp, tmp2, second = 0, ss = 0, res = 0;
  vector<long long> vv;
  for (int i = 1; i <= n; i++) {
    tmp = a[i];
    second += tmp;
    if (second >= p) {
      tmp2 = second - p;
      vv.push_back(a[i] - tmp2);
      a[i] = tmp2;
      res += get(vv);
      vv.clear();
      second = a[i];
      vv.push_back(a[i]);
    } else {
      vv.push_back(tmp);
    }
  }
  return res;
}
int main() {
  ios_base::sync_with_stdio(0);
  cin.tie(0);
  cout.tie(0);
  cin >> n;
  for (int i = 1; i <= n; i++) {
    cin >> a[i];
    aa[i] = a[i];
    sum += a[i];
  }
  fact();
  if (!v.size()) return cout << "-1\n", 0;
  long long ans = 1e18;
  for (int i = 0; i < v.size(); i++) {
    long long p = v[i];
    for (int j = 1; j <= n; j++) a[j] = aa[j] % p;
    ans = min(ans, solve(p));
  }
  cout << ans << "\n";
  return 0;
}
