#include <bits/stdc++.h>
using namespace std;
long long n, s, a[1000100], b[1000100], ans = 1e18;
void test(long long d) {
  long long t = 0;
  for (int i = 0; i < n; i++) b[i] = a[i];
  for (int i = 0; i < n; i++) {
    long long m = ((b[i] % d) + d) % d;
    if (m == 0) continue;
    if (b[i] > 0 and m < d - m) {
      b[i + 1] += m;
      t += m;
    } else {
      b[i + 1] -= d - m;
      t += d - m;
    }
  }
  ans = min(ans, t);
}
bool comp[1000100];
int main() {
  ios_base::sync_with_stdio(false);
  cin.tie(NULL);
  cin >> n;
  for (int i = 0; i < n; i++) {
    cin >> a[i];
    s += a[i];
  }
  if (s == 1) {
    cout << -1;
    return 0;
  }
  for (long long i = 2; i <= 1e6; i++) {
    if (comp[i]) continue;
    for (long long j = i * 2; j <= 1e6; j += i) {
      comp[j] = true;
    }
    if (s % i == 0) test(i);
    while (s % i == 0) s /= i;
  }
  if (s > 1) test(s);
  cout << ans;
}
