#include <bits/stdc++.h>
const int maxn = 1e6 + 3;
int n, a[maxn];
long long s;
std::vector<long long> p;
long long r[maxn];
struct pr {
  long long pos, cnt;
} st[maxn];
int stl;
long long solve(const long long &f) {
  long long ms = 0;
  for (int i = 0; i < n; ++i) {
    r[i] = a[i] % f;
    ms += r[i];
  }
  if (ms <= 0) return 0;
  long long sst = 0;
  long long ans = 0;
  long long hf = f / 2 + f % 2;
  for (int i = 0; i < n;) {
    if (!r[i]) {
      ++i;
      continue;
    }
    long long d = std::min(r[i], f - sst);
    st[stl++] = {i, d};
    sst += d;
    r[i] -= d;
    if (sst >= f) {
      long long cs = 0;
      int center;
      for (int j = 0; j < stl; ++j) {
        cs += st[j].cnt;
        if (cs >= hf) {
          center = j;
          break;
        }
      }
      long long mv = 0;
      for (int j = 0; j < stl; ++j) {
        mv += std::abs(st[j].pos - st[center].pos) * st[j].cnt;
      }
      ans += mv;
      sst = 0;
      stl = 0;
    }
    if (r[i] == 0) ++i;
  }
  return ans;
}
int main() {
  scanf("%d", &n);
  for (int i = 0; i < n; ++i) scanf("%d", a + i);
  s = 0;
  for (int i = 0; i < n; ++i) s += a[i];
  {
    long long m = s;
    for (long long i = 2; i * i <= s; ++i) {
      if (m % i == 0) {
        while (m % i == 0) m /= i;
        p.push_back(i);
      }
    }
    if (m != 1) {
      p.push_back(m);
    }
  }
  long long ans = std::numeric_limits<long long>::max();
  for (auto &&u : p) ans = std::min(ans, solve(u));
  if (ans < std::numeric_limits<long long>::max()) {
    printf("%lld\n", ans);
  } else {
    puts("-1");
  }
  return 0;
}
