#include <bits/stdc++.h>
#pragma GCC optimize("O3")
using namespace std;
const int maxN = 1 << 20;
const long long INF = 2000000000000000000ll;
int n;
long long T[maxN];
long long check(long long p) {
  long long res = 0, sum = 0;
  for (int i = (0); i < (int)(n); i++) {
    sum = (sum + T[i]) % p;
    res += min(sum, p - sum);
  }
  return res;
}
void solve() {
  scanf("%d", &n);
  long long m = 0;
  for (int i = (0); i < (int)(n); i++) {
    scanf("%lld", T + i);
    m += T[i];
  }
  if (m == 1ll) {
    printf("-1\n");
    exit(0);
  }
  long long res = INF;
  for (long long i = 2ll; i * i <= m; i++)
    if (m % i == 0) {
      res = min(res, check(i));
      while (m % i == 0) m /= i;
    }
  if (m != 1ll) res = min(res, check(m));
  printf("%lld\n", res);
}
int main() {
  int t;
  t = 1;
  while (t--) solve();
  return 0;
}
