#include <bits/stdc++.h>
using namespace std;
const int MAXN = 1e6;
int N;
long long A[MAXN + 10], B[MAXN + 10], S;
vector<long long> prime;
int main() {
  long long i, j;
  scanf("%d", &N);
  for (i = 1; i <= N; i++) scanf("%d", &A[i]), S += A[i];
  for (i = 2; i * i <= S; i++) {
    if (S % i == 0) {
      prime.push_back(i);
      while (S % i == 0) S /= i;
    }
  }
  if (S != 1) prime.push_back(S);
  long long ans = 1e18;
  for (auto now : prime) {
    long long aaa = 0;
    for (i = 1; i <= N; i++) B[i] = A[i];
    vector<long long> V;
    long long S = 0;
    for (i = 1; i <= N; i++) B[i] %= now;
    for (i = 1; i <= N; i++) {
      if (S + B[i] >= now)
        V.push_back(now - S), S += now - S;
      else
        V.push_back(B[i]), S += B[i];
      B[i] -= V.back();
      if (S == now) {
        long long t = 0;
        for (j = 0; j < V.size(); j++) {
          t += V[j];
          if (t >= (now + 1) / 2) break;
        }
        long long pos = j;
        for (j = 0; j < V.size(); j++) aaa += abs(pos - j) * V[j];
        V.clear();
        V.push_back(B[i]);
        S = B[i];
      }
    }
    ans = min(ans, aaa);
  }
  if (ans == 1e18) ans = -1;
  printf("%lld", ans);
}
