#include <bits/stdc++.h>
using namespace std;
using ll = long long;
const int N = 1000006;
int n, a[N];
int cp[N];
ll f(ll g) {
  for (int i = 0; i < n; i++) cp[i] = a[i];
  ll ans = 0;
  for (int i = 0; i < n; i++) {
    int j = i;
    ll s = cp[i] % g;
    while (j + 1 < n and s < g) {
      j++;
      s += cp[j] % g;
    }
    if (s < g) {
      break;
    }
    if (s != g) {
      cp[j] -= int(s - g);
    }
    ll l = 0, r = 0, sl = 0, sr = 0;
    for (int k = i + 1; k <= j; k++) {
      r += 1LL * (cp[k] % g) * (k - i);
      sr += (cp[k] % g);
    }
    ll tmp = l + r;
    for (int k = i + 1; k <= j; k++) {
      sl += cp[k - 1] % g;
      l += sl;
      r -= sr;
      sr -= cp[k] % g;
      tmp = min(tmp, l + r);
    }
    ans += tmp;
    i = j;
    if (s != g) {
      cp[j] = int(s - g);
      i--;
    }
  }
  return ans;
}
int main() {
  scanf("%d", &n);
  for (int i = 0; i < n; i++) scanf("%d", a + i);
  ll sum = 0;
  for (int i = 0; i < n; i++) sum += a[i];
  if (sum == 1) return printf("-1\n"), 0;
  ll ans = 1e18;
  for (ll i = 2; i * i <= sum; i++)
    if (sum % i == 0) {
      ans = min(ans, f(i));
      while (sum % i == 0) sum /= i;
    }
  if (sum > 1) ans = min(ans, f(sum));
  if (ans > 1e17) ans = -1;
  printf("%lld\n", ans);
}
