#include <bits/stdc++.h>
using namespace std;
mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());
const long long INF = (long long)2e18;
const int N = (int)1e6 + 77;
int n;
long long a[N];
long long solve(long long d) {
  long long ans = 0;
  long long cur = 0;
  for (int i = 0; i < n; i++) {
    long long h = a[i];
    long long z = min(h, d - cur);
    h -= z;
    cur += z;
    if (cur <= d / 2) ans += cur;
    if (cur > d / 2) ans += d - cur;
    if (cur == d) cur = 0;
    if (h > 0) {
      h %= d;
      cur = h;
      if (cur <= d / 2) ans += cur;
      if (cur > d / 2) ans += d - cur;
    }
  }
  if (cur != 0) throw;
  return ans;
}
int main() {
  scanf("%d", &n);
  long long sum = 0;
  for (int i = 0; i < n; i++) {
    scanf("%lld", &a[i]);
    sum += a[i];
  }
  if (sum == 1) {
    printf("-1\n");
    return 0;
  }
  long long ans = INF;
  for (long long x = 2; x * x <= sum; x++) {
    if (sum % x) continue;
    ans = min(ans, solve(x));
    while (sum % x == 0) sum /= x;
  }
  if (sum > 1) ans = min(ans, solve(sum));
  printf("%lld\n", ans);
  return 0;
}
