#include <bits/stdc++.h>
int n;
long long ans = 0x7fffffffffffffff, sum, p[1000002];
int a[1000002], b[1000002], c[1000002], pcnt;
inline int abs(int x) { return x > 0 ? x : -x; }
signed main() {
  scanf("%d", &n);
  for (register int i = 1; i <= n; i++) scanf("%d", &a[i]), sum += a[i];
  register long long temp = sum;
  for (register int i = 2; (long long)i * i <= temp;)
    if (sum % i == 0)
      sum /= i, p[++pcnt] = i;
    else
      i++;
  if (sum > 1) p[++pcnt] = sum;
  for (register long long _k = 1, k = p[_k]; _k <= pcnt; _k++, k = p[_k]) {
    if (p[_k] == p[_k - 1]) continue;
    long long res = 0;
    for (register int i = 1; i <= n; i++) b[i] = a[i] % k;
    for (register long long i = 1, last = 1, t = 0; i <= n;) {
      t += b[i];
      c[i] = b[i], b[i] = 0;
      if (t >= k) {
        c[i] -= t - k, b[i] = t - k;
        t = k;
        register int mid;
        register long long s = 0;
        for (mid = last; mid <= i; mid++) {
          s += c[mid];
          if (s >= (k + 1) / 2) break;
        }
        for (register int j = last; j <= i; j++)
          res += (long long)c[j] * abs(j - mid);
        t = 0, last = i;
      } else
        i++;
    }
    if (res < ans) ans = res;
  }
  printf("%I64d", ans == 0x7fffffffffffffff ? -1 : ans);
  return 0;
}
