#include <bits/stdc++.h>
#pragma GCC optimize("O3")
using namespace std;
int n, am[1000002], rst[1000002];
long long gg(long long a, long long b) {
  long long c;
  while (b) {
    c = a % b;
    a = b;
    b = c;
  }
  return a;
}
long long costmin = (1LL << 60);
long long tri(long long val) {
  long long ss = 0;
  for (int i = 1; i <= n; ++i) rst[i] = am[i] % val, ss += rst[i];
  if (ss == 0) return 0;
  if (ss % val != 0) return (1LL << 60);
  long long sc = 0;
  long long anstri = 0;
  deque<int> pz;
  for (int i = 1; i <= n; ++i) {
    if (rst[i]) {
      pz.push_back(i);
      sc += rst[i];
    }
    if (sc >= val) {
      long long s2 = 0;
      int medd = -1;
      for (int j = 0; j < pz.size(); ++j) {
        s2 += rst[pz[j]];
        if (s2 >= val / 2 + 1 && medd == -1) medd = pz[j];
      }
      s2 = 0;
      for (int j = 0; j < pz.size(); ++j) {
        if (j + 1 < pz.size())
          anstri += 1LL * rst[pz[j]] * abs(medd - pz[j]);
        else {
          anstri += 1LL * (val - s2) * abs(medd - pz[j]);
          rst[pz[j]] = rst[pz[j]] - (val - s2);
        }
        s2 += rst[pz[j]];
      }
      sc -= val;
      while (pz.size() >= 2) pz.pop_front();
    }
  }
  return anstri;
}
int main() {
  ios_base::sync_with_stdio(false);
  cin.tie(NULL);
  cin >> n;
  long long sum = 0;
  long long cmmdc;
  for (int i = 1; i <= n; ++i) {
    cin >> am[i], sum += am[i];
    if (i == 1 && am[i] != 0)
      cmmdc = am[i];
    else if (am[i] != 0)
      cmmdc = gg(cmmdc, am[i]);
  }
  if (cmmdc > 1) {
    cout << 0;
    return 0;
  }
  if (sum == 1) {
    cout << -1;
    return 0;
  }
  for (long long i = 2; i * i <= sum; ++i)
    if (sum % i == 0) {
      while (sum % i == 0) sum /= i;
      costmin = min(costmin, tri(i));
    }
  if (sum > 1) costmin = min(costmin, tri(sum));
  cout << costmin;
  return 0;
}
