#include <bits/stdc++.h>
using namespace std;
const int MX = 1000005;
const long long INF = 1000000000LL * 1000000000LL;
int a[MX];
int n;
long long Solve(long long p) {
  long long res = 0;
  long long pref_sum = 0;
  for (int i = 0; i < n; i++) {
    pref_sum = (pref_sum + a[i]) % p;
    res += min(pref_sum, p - pref_sum);
  }
  return res;
}
int main() {
  ignore = scanf("%d", &n);
  long long S = 0;
  for (int i = 0; i < n; i++) {
    ignore = scanf("%d", a + i);
    S += a[i];
  }
  vector<long long> pr;
  for (long long x = 2; x * x <= S; x++) {
    if (S % x == 0) {
      pr.push_back(x);
      while (S % x == 0) S /= x;
    }
  }
  if (S > 1) pr.push_back(S);
  long long ans = INF;
  for (auto p : pr) {
    ans = min(ans, Solve(p));
  }
  if (ans == INF) ans = -1;
  cout << ans << "\n";
}
