#include <bits/stdc++.h>
using namespace std;
const long long inf = 2e18;
int v[1000010], n;
long long dp[1000010], sum[1000010];
vector<long long> primes;
vector<pair<long long, int> > v1, aux, pos;
long long solve(long long x) {
  long long sol = 0;
  aux.clear();
  for (int i = 0; i < v1.size(); i++)
    aux.push_back({v1[i].first % x, v1[i].second});
  long long nr = 0;
  pos.clear();
  for (int i = 0; i < v1.size(); i++) {
    nr += aux[i].first;
    long long val = aux[i].first - max(0LL, nr - x);
    pos.push_back({val, aux[i].second});
    aux[i].first -= val;
    if (nr >= x) {
      long long sval = 0, sdp = 0, sol1 = inf;
      dp[pos.size()] = 0;
      sum[pos.size()] = 0;
      for (int j = pos.size() - 1; j >= 0; j--) {
        dp[j] = dp[j + 1] + 1LL * pos[j].second * pos[j].first;
        sum[j] = sum[j + 1] + pos[j].first;
      }
      for (int j = 0; j < pos.size(); j++) {
        sol1 = min(sol1, 1LL * pos[j].second * sval - sdp + dp[j + 1] -
                             1LL * pos[j].second * sum[j + 1]);
        sval += pos[j].first;
        sdp += 1LL * pos[j].second * pos[j].first;
      }
      sol += sol1;
      pos.clear();
      if (aux[i].first > 0) {
        pos.push_back({aux[i].first, aux[i].second});
        nr = aux[i].first;
      } else
        nr = 0;
    }
  }
  return sol;
}
int main() {
  scanf("%d", &n);
  long long s = 0;
  for (int i = 1; i <= n; i++) {
    scanf("%d", &v[i]);
    s += v[i];
  }
  long long ans = inf;
  if (s == 1) {
    printf("-1");
    return 0;
  }
  for (long long i = 2; i * i <= s; i++)
    if (s % i == 0) {
      primes.push_back(i);
      while (s % i == 0) s /= i;
    }
  if (s > 1) primes.push_back(s);
  for (int i = 1; i <= n; i++)
    if (v[i] > 0) v1.push_back({1LL * v[i], i});
  for (int i = 0; i < primes.size(); i++) ans = min(ans, solve(primes[i]));
  printf("%lld", ans);
  return 0;
}
