#include <bits/stdc++.h>
using namespace std;
long long n, a[1000005];
long long solve(long long p) {
  long long i;
  long long rem = 0, tmp = 0;
  for (i = 1; i <= n; i++) {
    rem = (a[i] + rem) % p;
    tmp += min(rem, (abs(rem - p)));
  }
  return tmp;
}
int main() {
  ios_base::sync_with_stdio(false);
  long long i, j;
  long long ans, tmp, sum = 0;
  cin >> n;
  for (i = 1; i <= n; i++) {
    cin >> a[i];
    sum += a[i];
  }
  if (sum == 0) return cout << "0" << endl, 0;
  if (sum == 1) return cout << "-1" << endl, 0;
  ans = LLONG_MAX;
  i = 0;
  for (j = 2; j * j <= sum; j++) {
    if (sum % j == 0) {
      tmp = solve(j);
      while (sum % j == 0) sum /= j;
      ans = min(ans, tmp);
    }
  }
  if (sum > 1) {
    tmp = solve(sum);
    ans = min(ans, tmp);
  }
  cout << ans << endl;
  return 0;
}
