#include <bits/stdc++.h>
using namespace std;
long long ara[1000006], b[1000006];
long long calc(int s, int e) {
  for (int i = s;; i++)
    if (b[i]) {
      s = i;
      break;
    }
  long long res = 0;
  while (s < e) {
    if (b[s] > b[e])
      res += b[e], b[e - 1] += b[e], e--;
    else
      res += b[s], b[s + 1] += b[s], s++;
  }
  return res;
}
long long func(int n, long long d) {
  for (int i = 0; i < n; i++) b[i] = (ara[i] % d);
  int st = 0;
  long long res = 0;
  int tot = 0;
  for (int i = 0; i < n; i++) {
    if (b[i] + tot >= d) {
      int x = (b[i] + tot - d);
      b[i] = d - tot;
      res += calc(st, i);
      st = i;
      b[i] = x;
      tot = x;
    } else
      tot += b[i];
  }
  return res;
}
int main() {
  int n;
  scanf("%d", &n);
  long long sum = 0;
  for (int i = 0; i < n; i++) scanf("%lld", &ara[i]), sum += ara[i];
  if (sum == 1) {
    printf("-1\n");
    return 0;
  }
  queue<long long> q;
  for (long long i = 2; i * i <= sum; i++) {
    if (!(sum % i)) {
      q.push(i);
      while (!(sum % i)) sum /= i;
    }
  }
  if (sum != 1) q.push(sum);
  long long res = 1000000000000000000ll;
  while (!q.empty()) {
    res = min(res, func(n, q.front()));
    q.pop();
  }
  printf("%lld\n", res);
  return 0;
}
