#include <bits/stdc++.h>
using namespace std;
const int N = 1000005;
int iter, a[N], arr[N];
inline vector<long long> get(long long n) {
  vector<long long> ret;
  for (long long x = 2; x * x <= n; x++) {
    if (n % x == 0) {
      ret.push_back(x);
      while (n % x == 0) {
        n /= x;
      }
    }
  }
  if (n > 1) ret.push_back(n);
  return ret;
}
inline long long compute(long long med) {
  long long cur = 0;
  for (int i = 0; i < iter; i++) {
    cur += arr[i];
    if (cur >= med) {
      long long ret = 0;
      long long tmp = 0;
      for (int j = 0; j < i; j++) {
        tmp += arr[j];
        ret += tmp;
      }
      tmp = 0;
      for (int j = iter - 1; j > i; j--) {
        tmp += arr[j];
        ret += tmp;
      }
      return ret;
    }
  }
  assert(false);
  return 0;
}
int main() {
  ios::sync_with_stdio(false);
  cin.tie(0);
  int n;
  cin >> n;
  long long sum = 0;
  for (int i = 1; i <= n; i++) {
    cin >> a[i];
    sum += a[i];
  }
  if (sum == 1) {
    cout << -1 << '\n';
    exit(0);
  }
  vector<long long> pFac = get(sum);
  long long answer = 1e18;
  for (long long x : pFac) {
    iter = 0;
    long long tot = 0;
    long long cur = 0;
    long long med = (x + 1) / 2;
    for (int i = 1; i <= n; i++) {
      int tmp = a[i] % x;
      if (cur + tmp < x) {
        arr[iter] = tmp;
        iter++;
        cur += tmp;
      } else if (cur + tmp == x) {
        arr[iter] = tmp;
        iter++;
        tot += compute(med);
        iter = 0;
        cur = 0;
      } else {
        arr[iter] = x - cur;
        iter++;
        tot += compute(med);
        cur = tmp - x + cur;
        arr[0] = cur;
        iter = 1;
      }
    }
    answer = min(answer, tot);
  }
  cout << answer << '\n';
  return 0;
}
