#include <bits/stdc++.h>
long long tt, x, y, z, sum, n, i, j, h, k, t, d, m, l, ll, rr, r, a[1000006],
    b[1000006], f[1000006];
using namespace std;
long long xl(long long i) {
  long long res = 0;
  for (j = 1; j <= d; j++) b[j] = a[j];
  l = 1;
  r = i;
  tt = 1;
  z = b[1];
  x = 1;
  while (r <= n) {
    if (b[x] > i) {
      l += b[x] - b[x] % i - i;
      r += b[x] - b[x] % i - i;
      b[x] -= (b[x] - b[x] % i - i);
    }
    y = 0;
    t = (l + r) / 2;
    while (z < t) tt++, z += a[tt];
    while (y < i) {
      if (b[x] > i - y) {
        res += (i - y) * abs(f[x] - f[tt]);
        b[x] -= (i - y);
        y = i;
      } else {
        res += b[x] * abs(f[x] - f[tt]);
        y += b[x];
        x++;
      }
    }
    l += i;
    r += i;
  }
  return res;
}
int main() {
  ios_base::sync_with_stdio(0);
  cin.tie(NULL);
  cin >> n;
  for (i = 1; i <= n; i++) {
    cin >> j;
    sum += j;
    if (j > 0) d++, a[d] = j, f[d] = i;
  }
  if (sum == 1)
    cout << -1;
  else {
    n = sum;
    i = 2;
    m = 1e18;
    while (i <= sqrt(sum)) {
      if (sum % i == 0) m = min(m, xl(i));
      while (sum % i == 0) sum /= i;
      i++;
    }
    if (sum > 1) m = min(m, xl(sum));
    cout << m;
  }
}
