#include <bits/stdc++.h>
using namespace std;
const int inf = (int)1e9 + 7;
const int N = (int)2e6 + 5;
int n;
int a[N];
long long b[N];
long long p[N], le[N], ri[N];
vector<long long> check;
long long solve(int l, int r, long long d) {
  long long cur = 0;
  long long toadd = 0;
  for (int i = l; i <= r; ++i) {
    le[i] = cur;
    toadd += b[i];
    cur += toadd;
  }
  cur = 0;
  toadd = 0;
  for (int i = r; i >= l; --i) {
    ri[i] = cur;
    toadd += b[i];
    cur += toadd;
  }
  long long to = LLONG_MAX;
  for (int i = l; i <= r; ++i) {
    to = min(to, le[i] + ri[i]);
  }
  return to;
}
int main() {
  ios_base ::sync_with_stdio(false);
  cin.tie(nullptr);
  cin >> n;
  for (int i = 1; i <= n; ++i) {
    cin >> a[i];
    p[i] = p[i - 1] + a[i];
  }
  long long to = p[n];
  if (to <= 1) {
    cout << "-1\n";
    return 0;
  }
  for (long long d = 2; d * d <= to; ++d) {
    if (to % d == 0) {
      check.push_back(d);
      while (to % d == 0) to /= d;
    }
  }
  if (to > 1) {
    check.push_back(to);
  }
  long long ans = LLONG_MAX;
  for (long long d : check) {
    for (int i = 1; i <= n; ++i) b[i] = a[i] % d;
    int i = 1;
    long long cur = 0;
    while (i <= n) {
      int j = i;
      long long sum = b[i];
      while (j + 1 <= n && sum < d) {
        sum += b[j + 1];
        ++j;
      }
      long long rem = !sum ? 0 : sum - d;
      b[j] -= rem;
      cur += solve(i, j, d);
      if (rem) {
        b[j] = rem;
        i = j;
      } else {
        i = j + 1;
      }
    }
    ans = min(ans, cur);
  }
  cout << ans;
  return 0;
}
