#include <bits/stdc++.h>
#pragma GCC optimize("Ofast")
using namespace std;
int n;
long long a[1000100];
long long sum;
vector<long long> v;
long long b[1000100];
long long temp[1000100];
int tempsz;
long long cal(long long k) {
  long long lei = 0;
  long long tar = (k + 1) / 2;
  int j;
  for (int i = 0; i < int(tempsz); i++) {
    if (lei + temp[i] < tar)
      lei += temp[i];
    else {
      j = i;
      break;
    }
  }
  long long ret = 0;
  for (int i = 0; i < int(tempsz); i++) ret += temp[i] * abs(i - j);
  return ret;
}
long long check(long long k) {
  for (int i = 1; i <= int(n); i++) b[i] = a[i] % k;
  tempsz = 0;
  long long lei = 0;
  long long ret = 0;
  for (int i = 1; i <= int(n); i++) {
    if (lei + b[i] <= k) {
      temp[tempsz] = b[i];
      tempsz++;
      lei += b[i];
    } else {
      temp[tempsz] = k - lei;
      tempsz++;
      b[i] -= (k - lei);
      ret += cal(k);
      tempsz = 0;
      lei = 0;
      i--;
      continue;
    }
  }
  ret += cal(k);
  return ret;
}
int main() {
  cin.tie(0);
  ios_base::sync_with_stdio(false);
  cin >> n;
  for (int i = 1; i <= int(n); i++) {
    cin >> a[i];
    sum += a[i];
  }
  if (sum == 1) {
    cout << -1 << endl;
    return 0;
  }
  long long ii;
  for (ii = 2; ii * ii <= sum; ii++) {
    if (sum % ii == 0) {
      v.push_back(ii);
      while (sum % ii == 0) sum /= ii;
    }
  }
  if (sum > 1) v.push_back(sum);
  long long mini = 1LL << 60;
  for (int i = 0; i < v.size(); i++) mini = min(mini, check(v[i]));
  cout << mini << endl;
}
