#include <bits/stdc++.h>
using namespace std;
const int nax = 1e6 + 111;
int n;
int a[nax];
long long b[nax];
long long sum;
vector<long long> primes;
long long best = 1e18;
vector<pair<long long, long long>> w;
long long opt = 0;
void proces(long long prime) {
  int L = w[0].first;
  int R = w.back().first;
  int wsk = 0;
  long long sum = 0;
  long long res = 1e18;
  long long ile = 0;
  long long global = 0;
  for (auto it : w) global += (long long)it.second * it.first;
  for (int i = L; i <= R; ++i) {
    while (wsk < (int)w.size() && w[wsk].first == i) {
      ile += w[wsk].second;
      sum += (long long)w[wsk].second * w[wsk].first;
      wsk += 1;
    }
    res = min(res, (long long)i * ile - sum + (global - sum) -
                       (long long)(prime - ile) * i);
  }
  opt += res;
}
int main() {
  scanf("%d", &n);
  for (int i = 1; i <= n; ++i) {
    scanf("%d", a + i);
    sum += a[i];
  }
  if (sum == 1) {
    printf("-1\n");
    return 0;
  }
  for (int i = 2; (long long)i * i <= sum; ++i) {
    if (sum % i == 0) {
      primes.push_back(i);
      while (sum % i == 0) sum /= i;
    }
  }
  if (sum > 1) primes.push_back(sum);
  for (auto it : primes) {
    opt = 0;
    long long mam = 0;
    for (int i = 1; i <= n; ++i) b[i] = a[i] % it;
    for (int i = 1; i <= n; ++i) {
      int take = min(it - mam, b[i]);
      mam += take;
      if (take > 0) w.push_back(make_pair(i, take));
      if (mam == it) {
        proces(it);
        w.clear();
        mam = 0;
      }
      b[i] -= take;
      take = min(it - mam, b[i]);
      mam += take;
      if (take > 0) {
        w.push_back(make_pair(i, take));
      }
    }
    best = min(best, opt);
  }
  printf("%lld\n", best);
  return 0;
}
