#include <bits/stdc++.h>
using namespace std;
int N;
long long a[1000005], b[1000005];
long long ans = 0x7ffffffe;
int era[1000005];
void solve(long long div) {
  if (div == 1) return;
  for (int i = 0; i < N; i++) b[i] = a[i] % div;
  long long candidate = 0;
  long long cursum = 0;
  vector<pair<int, int> > v;
  for (int i = 0; i < N; i++) {
    if (b[i] == 0) continue;
    if (cursum + b[i] < div) {
      cursum += b[i];
      v.push_back(make_pair(i, b[i]));
      continue;
    } else {
      v.push_back(make_pair(i, div - cursum));
      b[i] -= (div - cursum);
      long long midv = (div + 1) / 2, midc;
      long long chk = 0;
      for (auto it = v.begin(); it != v.end(); it++) {
        chk += it->second;
        if (chk >= midv) {
          midc = it->first;
          break;
        }
      }
      for (auto it = v.begin(); it != v.end(); it++)
        candidate += (long long)abs(it->first - midc) * it->second;
      i--;
      cursum = 0;
      v.clear();
    }
  }
  if (candidate < ans) ans = candidate;
}
int main() {
  ans *= ans;
  scanf("%d", &N);
  for (int i = 0; i < N; i++) scanf("%lld", &a[i]);
  long long sum = 0;
  for (int i = 0; i < N; i++) sum += a[i];
  if (sum == 1) {
    printf("-1\n");
    return 0;
  }
  if (sum % 2 == 0) {
    solve(2);
    while (sum % 2 == 0) sum /= 2;
  }
  for (int i = 3; i <= 1000000; i += 2) {
    if (era[i] == 0) {
      for (int j = i * 3; j <= 1000000; j += i * 2) era[j] = 1;
      if (sum % i == 0) {
        solve(i);
        while (sum % i == 0) sum /= i;
      }
    }
  }
  if (sum != 1) {
    solve(sum);
  }
  printf("%lld\n", ans);
  return 0;
}
