#include <bits/stdc++.h>
using namespace std;
const int MAXN = 1010101;
vector<int> primes;
vector<bool> iscomp(MAXN);
void init() {
  iscomp[0] = true;
  iscomp[1] = true;
  for (int i = 2; i < MAXN; i++) {
    if (!iscomp[i]) {
      primes.push_back(i);
      for (long long j = i * (long long)i; j < MAXN; j += i) iscomp[j] = true;
    }
  }
}
int main() {
  ios_base::sync_with_stdio(false);
  cin.tie(NULL);
  init();
  int n;
  cin >> n;
  vector<long long> a(n);
  for (int i = 0; i < n; i++) cin >> a[i];
  long long sum = 0;
  for (int i = 0; i < n; i++) sum += a[i];
  if (sum == 1) {
    cout << "-1\n";
    return 0;
  }
  vector<long long> possible_k;
  for (int i = 0; i < primes.size(); i++) {
    if (sum % primes[i] == 0) {
      possible_k.push_back(primes[i]);
      while (sum % primes[i] == 0) sum /= primes[i];
    }
  }
  if (sum != 1) possible_k.push_back(sum);
  long long ans = 0x3f3f3f3f3f3f3f3fLL;
  for (int i = 0; i < possible_k.size(); i++) {
    int midpoint = -1;
    long long leftover = 0;
    long long k = possible_k[i];
    long long cur = 0;
    for (int j = 0; j < n; j++) {
      if (leftover > 0 && leftover + a[j] >= k) {
        if (midpoint != -1) {
          cur += (j - midpoint) * (k - leftover);
        }
        midpoint = -1;
      }
      leftover = (leftover + a[j]) % k;
      if (midpoint == -1) {
        if (leftover * 2 >= k) {
          midpoint = j;
        } else {
          cur += leftover;
        }
      } else {
        cur += (j - midpoint) * a[j];
      }
    }
    ans = min(ans, cur);
  }
  cout << ans << '\n';
  return 0;
}
