#include <bits/stdc++.h>
using namespace std;
long long ar[1000050];
long long b[1000050];
long long prime[1000050];
long long fact[1666];
long long sz = 0;
int main() {
  ios_base::sync_with_stdio(false);
  cin.tie(NULL);
  cout.tie(NULL);
  long long n;
  cin >> n;
  for (int i = 2; i < 1000050; i++) {
    if (prime[i]) continue;
    for (int j = i + i; j < 1000050; j += i) prime[j] = 1;
  }
  for (long long i = 0; i < n; i++) cin >> ar[i];
  long long sum = 0;
  for (long long i = 0; i < n; i++) sum += ar[i];
  if (sum == 1) {
    cout << "-1";
    return 0;
  }
  for (long long i = 2; i * i <= sum; i++) {
    if (prime[i]) continue;
    if (sum % i == 0) {
      fact[sz++] = i;
      while (sum % i == 0) sum /= i;
    }
  }
  if (sz == 0 || sum > 1) fact[sz++] = sum;
  long long ed = 4e18;
  for (int i = 0; i < sz; i++) {
    long long cu = fact[i];
    long long half = cu / 2LL;
    if (cu % 2 == 1) half++;
    for (int j = 0; j < n; j++) b[j] = ar[j];
    long long ans = 0;
    for (int j = 0; j < n; j++) {
      if (b[j] >= cu) {
        b[j] %= cu;
      }
      long long tmp = 0;
      int k = j;
      long long cont = 0;
      long long mid = -1;
      while (k < n && tmp < cu) {
        tmp += b[k++];
        if (tmp >= half && mid == -1) mid = k - 1;
      }
      k--;
      if (mid == -1) mid = j;
      for (int l = j; l < k; l++) {
        cont += b[l] * abs(l - mid);
      }
      if (tmp >= cu) {
        long long ext = b[k] - (tmp - cu);
        cont += abs(k - mid) * ext;
        b[k] -= ext;
      }
      ans += cont;
      j = k;
      if (b[j]) j--;
    }
    ed = min(ed, ans);
  }
  cout << ed;
  return 0;
}
