#include <bits/stdc++.h>
using namespace std;
long long n;
long long ans;
long long tot, cnt, k;
long long a[1000050];
long long solve(long long d) {
  long long pre = 0, tmp = 0;
  for (int i = 1; i <= n; i++) {
    pre = (pre + a[i]) % d;
    tmp += min(pre, d - pre);
  }
  return tmp;
}
int main() {
  ios::sync_with_stdio(false), cin.tie(0), cout.tie(0);
  cin >> n;
  for (int i = 1; i <= n; i++) {
    cin >> a[i];
    tot += a[i];
  }
  if (tot == 1)
    ans = -1;
  else {
    ans = 1LL << 60;
    for (long long i = 2; i * i <= tot; i++) {
      if (tot % i == 0) {
        ans = min(ans, solve(i));
        while (tot % i == 0) tot /= i;
      }
    }
    if (tot > 1) ans = min(ans, solve(tot));
  }
  cout << ans << endl;
  return 0;
}
