#include <bits/stdc++.h>
using namespace std;
int a[1000005], n;
long long sum, m;
int main() {
  scanf("%d", &n);
  for (int i = 0; i < n; i++) scanf("%d", a + i), sum += a[i];
  if (sum == 1) {
    puts("-1");
    return 0;
  }
  vector<int> v;
  m = sum;
  for (int i = 2; i * i <= m; i++) {
    if (m % i == 0) {
      v.push_back(i);
      while (m % i == 0) m /= i;
    }
  }
  if (m != 1) v.push_back(m);
  long long ans = 1e15;
  for (int p : v) {
    long long q = 0;
    int l = 0, lval = a[0] % p, r = 1, rval = a[1] % p;
    while (l < n && r < n) {
      if ((lval < (p + 1) / 2)) {
        q += 1ll * (r - l) * lval, l = r, lval = (rval + lval) % p, r = r + 1;
        rval = a[r] % p;
      } else {
        if (lval + rval <= p) {
          q += (1ll * rval * (r - l));
          lval = (lval + rval) % p;
          r++;
          rval = a[r] % p;
        } else {
          q += 1ll * (r - l) * (p - lval);
          lval = (rval - (p - lval));
          l = r;
          r = r + 1;
          rval = a[r] % p;
        }
      }
    }
    ans = min(ans, q);
  }
  printf("%I64d", ans);
}
