#include <bits/stdc++.h>
using namespace std;
using ll = long long;
using ld = long double;
using pll = pair<ll, ll>;
using vll = vector<ll>;
using vpll = vector<pll>;
using gr = vector<vll>;
using wgr = vector<vpll>;
struct d_ {
  template <typename T>
  d_ &operator,(const T &x) {
    cerr << ' ' << x;
    return *this;
  }
  template <typename T>
  d_ &operator,(const vector<T> &x) {
    for (auto x : x) cerr << ' ' << x;
    return *this;
  }
} d_t;
vll uniqFact(ll n) {
  vll res;
  ll f = 2;
  while (f * f <= n) {
    if ((n % f) == 0) res.push_back(f);
    while ((n % f) == 0) n /= f;
    f++;
  }
  if (n > 1) res.push_back(n);
  return res;
}
ll n;
vll v;
long long tr(ll w) {
  long long ret = 0, cnt = 0;
  vpll pos;
  for (ll i(0); i < n; i++) {
    ll cur = v[i] % w;
    cnt += cur;
    if (cnt >= w) {
      ll rest = cnt - w;
      pos.push_back({i, cur - rest});
      ll sm = 0, med;
      for (auto &j : pos) {
        sm += j.second;
        if (2 * sm >= w) {
          med = j.first;
          break;
        }
      }
      for (auto &j : pos) {
        ret += j.second * (long long)abs(j.first - med);
      }
      pos.clear();
      cnt = rest;
      if (rest) pos.push_back({i, rest});
    } else
      pos.push_back({i, cur});
  }
  return ret;
}
int main(void) {
  ios_base::sync_with_stdio(false);
  cin >> n;
  v = vll(n);
  for (ll i(0); i < n; i++) cin >> v[i];
  long long cnt = 0;
  for (ll i(0); i < n; i++) cnt += v[i];
  if (cnt == 1) {
    cout << -1 << endl;
    return 0;
  }
  auto f = uniqFact(cnt);
  long long ret = (1LL << 60);
  for (auto &i : f) {
    ret = min(ret, tr(i));
  }
  cout << ret << endl;
  return 0;
}
