#include <bits/stdc++.h>
using namespace std;
void warp() {
  cin.tie(0);
  cout.tie(0);
  ios_base::sync_with_stdio(false);
}
long long get(vector<long long> &a, vector<long long> &b) {
  long long ans = 0;
  long long all = 0;
  long long n = a.size();
  for (long long i = 0; i < n; i++) all += b[i];
  long long cur = b[0], tar = 0;
  while (cur < all - cur) {
    tar++;
    cur += b[tar];
  }
  for (long long i = 0; i < n; i++) {
    ans += b[i] * abs(a[i] - a[tar]);
  }
  return ans;
}
long long check(long long need, vector<long long> a) {
  long long ans = 0;
  long long n = a.size();
  vector<long long> cur;
  vector<long long> b;
  long long s = 0;
  for (long long i = 0; i < n; i++) {
    a[i] %= need;
    if (a[i]) {
      cur.push_back(i);
      b.push_back(a[i]);
    }
    s += a[i];
    if (s >= need && b.size()) {
      b.back() -= (s - need);
      ans += get(cur, b);
      cur.clear();
      b.clear();
      s -= need;
      if (s == 0) continue;
      cur.push_back(i);
      b.push_back(s);
    }
  }
  return ans;
}
long long solve(long long n, vector<long long> a) {
  long long cnt = 0;
  for (long long i = 0; i < n; i++) cnt += a[i];
  if (cnt == 1) {
    return -1;
  }
  long long ans = check(cnt, a);
  vector<bool> prime(1e6 + 1, true);
  for (long long i = 2; i * i <= cnt; i++) {
    if (cnt % i) continue;
    while (cnt % i == 0) cnt /= i;
    ans = min(ans, check(i, a));
  }
  if (cnt > 1) ans = min(ans, check(cnt, a));
  return ans;
}
const long long maxn = 1e6;
void gen(vector<long long> &a) {
  long long n = a.size();
  for (long long i = 0; i < n; i++) a[i] = rand() % 20;
  long long s = 0;
  for (long long i = 0; i < n; i++) s += a[i];
  if (s == 0) a[0] = 1;
}
signed main() {
  warp();
  long long n;
  cin >> n;
  vector<long long> a(n);
  for (long long i = 0; i < n; i++) {
    cin >> a[i];
  }
  cout << solve(n, a) << endl;
  return 0;
}
